我正在 Memory Model 上阅读 Bjarne 的常见问题解答, 这是一段话
So, C++11 guarantees that no such problems occur for "separate memory locations.'' More precisely: A memory location cannot be safely accessed by two threads without some form of locking unless they are both read accesses. Note that different bitfields within a single word are not separate memory locations, so don't share structs with bitfields among threads without some form of locking. Apart from that caveat, the C++ memory model is simply "as everyone would expect.''
However, it is not always easy to think straight about low-level concurrency issues. Consider:
start with x==0 and y==0
if (x) y = 1; // Thread 1
if (y) x = 1; // Thread 2
Is there a problem here? More precisely, is there a data race? (No there isn't).
我的问题是,为什么没有数据竞争?对我来说很明显,显然存在数据竞争,因为线程 1 是 y
的编写器,而线程 2 是 y
的读取器,同样是 x
。
最佳答案
x
和 y
是 0
因此 if
后面的代码将不会被执行没有写入,因此不会有数据竞争。
关于c++ - 为什么没有数据竞赛?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43104573/