문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top