- Test and Test-and-set
In
computer science , thetest-and-set CPU instruction is used to implementmutual exclusion inmultiprocessor environments. Although a correct lock can be implemented with test-and-set, it can lead tomemory contention in busy lock (caused by bus locking and cache invalidation when test-and-set operation needs to access memory atomically).To lower the overhead a more elaborate locking protocol test and test-and-setis used. The main idea is "not" to spin in test-and-set but increase the likelihood of successful test-and-set by using following entry protocol to the lock:
"boolean" locked := false "// shared lock variable" procedure EnterCritical() { do { while (locked = true) skip "// spin until lock "seems" free } while TestAndSet(locked) "// actual atomic locking" }
Exit protocol is: procedure ExitCritical() { locked := false }
The entry protocol uses normal memory reads to spin, waiting for the lock to become free. Test-and-set is only used to try to get the lock when normal memory read says it's free. Thus the expensive atomic memory operations happens less often than in simple spin around test-and-set.
If the
programming language used supportsshort-circuit evaluation , the entry protocol could be implemented as:procedure EnterCritical() { while ( locked = true or TestAndSet(locked) = true ) skip "// spin until locked" }
Caveat
Although this optimization is useful in
system programming it should be avoided in high levelconcurrent programming . One example of bad usage of thisidiom isdouble-checked locking , which is listed as ananti-pattern .ee also
*
Parallel processor
*Parallel programming
*Mutual exclusion
*Test-and-set References
* Gregory R. Andrews, "Foundations of Multithreaded, Parallel, and Distributed Programming", pp. 100-101. Addison-Wesley, 2000. ISBN 0-201-35752-6.
Wikimedia Foundation. 2010.