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

C ++ 0x defines the std::atomic pattern for safe atom access to variables. This template contains, among other things, a member function std :: atomic :: exchange , which atomically saves the new value in "this" and retrieves the existing value of "this".

Win32 has a similar function: InterlockedExchange

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

What I do not understand is the point of view of this operation. The return value is "meaningless" because as soon as I can check the return value, another thread may already have overwritten it.

So what is the use case for this? What can information about what value was there before I write a new value in a variable tell me?

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

+6
source share
1 answer

Your typical spin lock:

 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 the Herb Sutter waiting line for a real application.

+8
source

Source: https://habr.com/ru/post/894699/


All Articles