Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use case for the atomic exchange (read-write) operation?

C++0x specifies the std::atomic template for thread safe atomic access to variables. This template has, among others, a member function std::atomic::exchange that atomically stores a new value in "this" and retrieves the existing value of "this".

Win32 has a similar function: InterlockedExchange

Now, what these operations do is simple: atomic read-modify.

What I do not understand is what the point of this operation is. The value read that is returned is "meaningless", because once I can inspect the return value, another thread may already have overwritten it.

So what's the use case for this? What can the information of which value was there just before I wrote my new value into the variable tell me?

Note: The compare_exchange / InterlockedCompareExchange semantics do make sense to me, but not the simple exchange semantics.

like image 748
Martin Ba Avatar asked Aug 10 '11 08:08

Martin Ba


1 Answers

Your typical spinlock:

std::atomic<bool> lock;  // initialize to false

{ // some critical section, trying to get the lock:

  while (lock.exchange(true)) { }  // now we have the lock

  /* do stuff */

  lock = false; // release lock
}

See Herb Sutter's wait-free queue for a real-world application.

like image 147
Kerrek SB Avatar answered Nov 06 '22 22:11

Kerrek SB