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

房东的猫 提交于 2020-05-11 06:29:30

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/7007834/what-is-the-use-case-for-the-atomic-exchange-read-write-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!