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.
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.
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