全局变量在2个不同核心上的2个并发运行线程之间共享.线程写入和读取变量.对于原子变量,一个线程可以读取过时值吗?每个核心可能在其缓存中具有共享变量的值,并且当一个线程在缓存中写入其副本时,不同核心上的另一个线程可能从其自己的缓存中读取过时值.或者编译器执行强大的内存排序以从其他缓存中读取最新值?c ++ 11标准库具有std :: atomic支持.这与volatile关键字有何不同?在上述场景中,volatile和atomic类型的行为方式有何不同?
#include <thread>
#include <atomic>
#include <cassert>
std::atomic<bool> x = {false};
std::atomic<bool> y = {false};
std::atomic<int> z = {0};
void write_x()
{
x.store(true, std::memory_order_seq_cst); // #1
}
void write_y()
{
y.store(true, std::memory_order_seq_cst); // #2
}
void read_x_then_y()
{
while (!x.load(std::memory_order_seq_cst)) // #3
;
if (y.load(std::memory_order_seq_cst)) { // #4
++z;
}
}
void read_y_then_x()
{
while (!y.load(std::memory_order_seq_cst)) // #5
;
if (x.load(std::memory_order_seq_cst)) { // #6
++z;
}
}
int main()
{
std::thread a(write_x);
std::thread b(write_y);
std::thread c(read_x_then_y);
std::thread d(read_y_then_x); …Run Code Online (Sandbox Code Playgroud)