【发布时间】:2022-01-23 06:26:55
【问题描述】:
我想知道,memory_order_relaxed 是否允许在同一个线程上不受约束地重新排序代码?例如:
// All on the same thread
std::atomic_int num(10);
std::cout << num.load(memory_order_relaxed) << "\n";
num.store(0, memory_order_relaxed);
是否可以打印 0? (在实际代码中另一个线程正在修改num,但它无关)
【问题讨论】:
-
如果没有其他线程正在修改它,则排序不会有任何区别。只有两个线程同时对同一事物进行操作,顺序才是重要的。
-
@DavidSchwartz 哦,好的。所以在这个例子中,不可能打印 0,对吧?
-
没有。并且操作发生的顺序并不重要,因为没有其他线程在观察它们。也许 0 的写入是在加载执行之前被发送到内存的,但是你怎么知道呢?没有人在看那个。
-
Maybe the write of 0 is emitted to memory before the load is executed, but how could you tell等等,这有可能吗? -
有可能,但你永远无法判断。没有人观察到这种行为。
标签: c++ multithreading atomic