After reading the Test-and-Set Wikipedia entry, I am still left with the question "What would a Test-and-Set be used for?"
I realize that you can use it to implement Mutex (as described in wikipedia), but what other uses does it have?
Test-and-set is an atomic RMW operation that sets the value at a memory location to 1 and returns the old value (either 1 or 0 ). There is no "true" test-and-set operation in Java but you can simulate it by passing 1 to AtomicInteger::getAndSet and expecting it to return 1 or 0 .
Test and Set Lock –Test and Set Lock (TSL) is a synchronization mechanism. It uses a test and set instruction to provide the synchronization among the processes executing concurrently.
Test and Set Lock This instructions reads the contents of a memory location, stores it in a register and then stores a non-zero value at the address. This operation is guaranteed to be indivisible. That is, no other process can access that memory location until the TSL instruction has finished.
A good example is "increment."
Say two threads execute a = a + 1
. Say a
starts with the value 100
. If both threads are running at the same time (multi-core), both would load a
as 100
, increment to 101
, and store that back in a
. Wrong!
With test-and-set, you are saying "Set a
to 101
, but only if it currently has the value 100
." In this case, one thread will pass that test but the other will fail. In the failure case, the thread can retry the entire statement, this time loading a
as 101
. Success.
This is generally faster than using a mutex because:
You use it any time you want to write data to memory after doing some work and make sure another thread hasn't overwritten the destination since you started. A lot of lock/mutex-free algorithms take this form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With