Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Test-and-Set used for?

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?

like image 253
Benoit Avatar asked Sep 23 '08 13:09

Benoit


People also ask

What is test and set in Java?

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 .

Is test and set a locking mechanism?

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.

What kind of solution is test and set lock TSL provide?

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.


2 Answers

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:

  1. Most of the time there isn't a race condition, so the update happens without having to acquire some sort of mutex.
  2. Even during collision, one thread isn't blocked at all, and it's faster for the other thread to just spin and retry than it would be to suspend itself in line for some mutex.
like image 183
Jason Cohen Avatar answered Oct 16 '22 14:10

Jason Cohen


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.

like image 21
moonshadow Avatar answered Oct 16 '22 16:10

moonshadow