我无法理解奇怪的 std::atomic_short.load() 行为
I can't understand weird std::atomic_short.load() behavior
我很难理解C++11 std::atomic_short行为的一部分
我将0或255设置为atomic_short变量的值
但是.load()表示该值既不是0也不是255。
我想要一个线程来写原子变量,我想要另一个线程读取它
环境:
英特尔酷睿i5
OSX 10.11.6
clang(Xcode7.3.1)
#include <iostream>
#include <atomic>
#include <thread>
std::atomic_short value = ATOMIC_VAR_INIT(0);
void process1() {
bool flag = false;
for (int i = 0; i < 100000; ++i){
std::this_thread::yield;
if (flag){
value.store(255);
} else {
value.store(0);
}
flag = !flag;
}
}
void process2() {
for (int i = 0; i < 100000; ++i){
std::this_thread::yield;
if (value.load() != 255 && value.load() != 0){
printf("warningA! %dn", i);
}
}
}
int main(int argc, char** argv) {
value.store(0);
std::thread t1(process1);
std::thread t2(process2);
t1.join();
t2.join();
return 0;
}
warningA! 3
warningA! 1084
warningA! 1093
问题是您有两个单独的load
,这使得您的比较不是原子的。相反,load
值一次,然后比较:
void process2() {
for (int i = 0; i < 100000; ++i){
std::this_thread::yield;
auto currentValue = value.load();
if (currentValue != 255 && currentValue != 0){
printf("warningA! %dn", i);
}
}
}
实例
相关文章:
- 如何从 std::atomic 中提取指针 T<T>?
- 'short int'持有的值溢出,但"自动"不会溢出?
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- std::memory_order for std::atomic:<T>:wait
- 我应该删除矢量<short>吗?
- MESI协议和std::atomic-它是否确保所有写入立即对其他线程可见?
- 在 lambda 表达式中使用 std::atomic
- C++std::atomic在程序员级别保证了什么
- 如果在 2 个线程中使用,是否值得将size_t声明为 std::atomic?
- MyType 允许 std::atomic 的确切要求是什么<MyType>?
- 无法将类型"T&"的非常量左值引用绑定到类型"T"的右值 t++ std::atomic<T>
- gcc Atomic在gcc 4.1.1中内置了奇怪的行为
- 在 C++20 之前和之后初始化 std::atomic
- Red Hat:使用<atomic>编译很好,但链接器找不到__atomic_store_16;什么库?
- std::atomic 和 std::mutex 的相对性能
- 使用用户定义的类型 UDT 实例化 std::atomic<>。如果 UDT 具有虚函数,则 l 墨水将失败。为什么?
- 简单使用 std::atomic 在两个线程之间共享数据
- Port pthread_cond_broadcast to std::atomic
- std::atomic中的任何内容都是免费等待的
- 对于 CPU 无法原子操作的类型,std::atomic 有什么意义?