c++ operator |= atomic 是多核处理器吗?

Is the c++ operator |= atomic with a multicore processor?

我目前正在与另一位开发人员进行辩论,他向我保证以下 c++ 语句是原子的:

x |= 0x1; // x is shared by multiple threads

在发布模式下使用 VC++11 编译生成以下程序集:

01121270  or          dword ptr ds:[1124430h],1

另一位开发人员说位操作是原子的,因此是线程安全的。我对英特尔 i7 处理器的体验与此相反。

我认为对于多核处理器,任何共享内存写入都是不安全的,因为有单独的处理器缓存。但是做了更多研究后,似乎 x86 处理器提供了一些与 processors/cores 之间的内存操作顺序相关的保证,这表明它 应该 是安全的......再次,根据我的经验,情况似乎并非如此。

由于我对这些事情没有权威的知识,所以我很难提出我的理由,甚至很难相信我是对的。

不,它绝对不能保证是原子的。是否使用可中断指令(序列)来实现取决于编译器和平台。但是从标准的角度来看,它不是原子的;因此,如果一个线程执行 x |= 0x1; 而另一个线程访问 x 而两者之间没有同步点,则为未定义行为(数据竞争)。

来自 C++11 的支持引述:

1.10/5:

The library defines a number of atomic operations (Clause 29) and operations on mutexes (Clause 30) that are specially identified as synchronization operations. ...

第29条介绍std::atomic及相关功能。它没有将基本类型指定为原子类型。

1.10/21:

The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior. ...