原子交换(读写)操作的用例是什么?
C++0x 指定用于对变量进行线程安全原子访问的 std::atomic
模板。除其他外,该模板还具有成员函数 std::atomic: :exchange,原子地在“this”中存储一个新值并检索“this”的现有值。
Win32 有类似的功能:InterlockedExchange
现在,这些操作的作用很简单:原子读取-修改。
我不明白的是这个操作的点是什么。返回的读取值是“无意义的”,因为一旦我可以检查返回值,另一个线程可能已经覆盖了它。
那么这个的用例是什么? 在将新值写入变量之前,该值的信息可以告诉我什么?
注意:compare_exchange
/ InterlockedCompareExchange
语义对我来说确实有意义,但不是简单的交换语义。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
典型的自旋锁:
有关实际应用程序,请参阅 Herb Sutter 的免等待队列。
Your typical spinlock:
See Herb Sutter's wait-free queue for a real-world application.