这是原子读写bool的正确方法吗? [英] Is this the correct way to atomically read and write a bool?

查看:116
本文介绍了这是原子读写bool的正确方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

布尔值标志由两个线程切换.下面的代码有意义吗?

A boolean flag is toggled by two threads. Does the following code make sense?

static bool ATOMIC_BOOL_READ( volatile bool& var )
{
    return __sync_fetch_and_or(&var, 0);
}

static void ATOMIC_BOOL_WRITE(volatile bool& var, bool newval )
{
    __sync_bool_compare_and_swap( &var, !newval, newval);
}

请注意以下几点:

  • 我正在传递布尔参考.有道理吗?

  • I am passing in a bool reference. Make sense?

为了踢球,我还宣布它是易变的.

For kick's sake, I am also declaring it volatile.

更新:

我想问的基本问题是: 原子性和记忆障碍之间有什么区别?如果线程A在变量foo上执行 atomic Builtin ,则线程B无法对变量foo进行任何操作;否则,线程B不能执行任何操作.从而造成记忆障碍?

The fundamental question I want to ask is: Whats the difference between atomicity and memory barrier? If Thread A is executing an atomic builtin on variable foo, then Thread B cannot do ANYTHING on variable foo; hence creating a memory barrier?

推荐答案

原子本质上是不可移植的,这些是GCC扩展,将来可能不再存在,无法在其他版本上使用编译器.

Atomics are intrinsically non-portable and these are GCC extensions that might not exist anymore in the future and won't work on other compilers.

只有在完全理解以上陈述之后,您才应该阅读其余的答案.

You should read the rest of the answer only once you understood completely the above statement.

一个值得注意的事实是,所有现有计算机始终保证访问特定大小的数据是原子的.这来自于基本概念,即内存和系统总线中的数据以一定的粒度进行传输.在大多数机器中,布尔绝对应该是原子的,所以:

A notable fact is that ALL machines existing have always guaranteed that access to data up to a certain size is atomic. This comes from the basic notion that data in memory and in the system bus is transfered with a certain granularity. A boolean should definitively be atomic in most machines, so:

bool ATOMIC_BOOL_READ(volatile bool* b) {
    bool v = *b;
    __sync_synchronize(); // ensure value pushed to memory
    return v;
}

void ATOMIC_BOOL_WRITE(volatile bool* b, bool v) {
    __sync_synchronize(); // read will return fresh value
   *b = v;
}

这可能是GCC不提供简单的加载/存储特殊原子操作的原因:它们已经被认为是原子操作.

That is probably the reason why GCC does not provide simple load/store special atomic operations: they are already supposed to be atomic.

这篇关于这是原子读写bool的正确方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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