原子交换(读写)操作的用例是什么? [英] What is the use case for the atomic exchange (read-write) operation?

查看:105
本文介绍了原子交换(读写)操作的用例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 0x指定用于线程安全原子访问变量的std::atomic模板.除其他外,该模板具有成员函数 std :: atomic: :exchange 以原子方式在"this"中存储一个新值,并检索"this"的现有值.

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具有类似的功能:

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?

注意:compare_exchange/InterlockedCompareExchange语义对我来说确实有意义,但简单的交换语义却不可行.

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

推荐答案

您的典型自旋锁:

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
}

有关实际应用程序,请参见Herb Sutter的无等待队列.

See Herb Sutter's wait-free queue for a real-world application.

这篇关于原子交换(读写)操作的用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆