std :: atomic是c ++ 11引入的新功能,但我找不到很多关于如何正确使用它的教程.那以下的做法是否通用又高效?
我使用的一种做法是我们有一个缓冲区,我想在一些字节上使用CAS,所以我做的是:
uint8_t *buf = ....
auto ptr = reinterpret_cast<std::atomic<uint8_t>*>(&buf[index]);
uint8_t oldValue, newValue;
do {
oldValue = ptr->load();
// Do some computation and calculate the newValue;
newValue = f(oldValue);
} while (!ptr->compare_exchange_strong(oldValue, newValue));
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:
编辑:如果这些问题依赖于处理器/体系结构,那么x86/x64处理器的结论是什么?
我的类型程序中有一个原子变量atomic<int>。在某些地方,我不需要以原子方式访问其中的值,因为我只是检查它是否为 0。换句话说,在这些情况下,我想避免在原子访问时发生的总线锁定等开销。
如何以非原子方式访问原子变量。使用 (int) 对其进行类型转换是否足够,如下所示?如果没有,我认为,我该怎么做?
atomic<int> atm;
int x;
........
x = (int)atm; // Would this be a non-atomic access, no bus locking et all?
Run Code Online (Sandbox Code Playgroud)