c++ - 为什么没有数据竞赛?

标签 c++ multithreading c++11

我正在 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

最佳答案

xy0 因此 if 后面的代码将不会被执行没有写入,因此不会有数据竞争。

关于c++ - 为什么没有数据竞赛?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43104573/

相关文章:

c - C 中的线程(和 irq)安全动态内存处理程序

c# - 在 PostgreSQL 中锁定表

c++ - 模 : The Purpose of An Undefined Integer

c++ - 如何使用chdir更改目录?

c# - Code Contracts - 不错,处于边缘,但还没有准备好迎接黄金时段?

c++ - OpenGL 试图平移对象,但相机也平移,我不需要

c++ - 使用 extern const 的函数初始化 const

c++ - 将 STL list<string> 转换为 vector<string> c++11

c++ - 了解堆栈数据结构并实现它

c++ - 如何通过引用 O(1) 在 C++ 中复制 vector ?