C ++内存模型-此示例是否包含数据竞争? [英] C++ memory model - does this example contain a data race?

查看:64
本文介绍了C ++内存模型-此示例是否包含数据竞争?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Bjarne Stroustrup的C ++ 11常见问题解答,但在理解内存模型部分。

I was reading Bjarne Stroustrup's C++11 FAQ and I'm having trouble understanding an example in the memory model section.

他给出了以下代码段:

// start with x==0 and y==0
if (x) y = 1; // thread 1
if (y) x = 1; // thread 2

常见问题解答说这里没有数据竞赛。我不明白线程1读取内存位置 x 并由线程2写入,而没有任何同步( y )。这是两次访问,其中之一是写操作。

The FAQ says there is not a data race here. I don't understand. The memory location x is read by thread 1 and written to by thread 2 without any synchronization (and the same goes for y). That's two accesses, one of which is a write. Isn't that the definition of a data race?

此外,它还说:(我所知道的)当前的每个C ++编译器都给出了正确的答案。这个正确的答案是什么?答案是否会根据一个线程的比较是在另一个线程的写操作之前还是之后发生(或者另一个线程的写操作甚至对读取线程可见)而有所不同?

Further, it says that "every current C++ compiler (that I know of) gives the one right answer." What is this one right answer? Couldn't the answer vary depending on whether one thread's comparison happens before or after the other thread's write (or if the other thread's write is even visible to the reading thread)?

推荐答案

// start with x==0 and y==0
if (x) y = 1; // thread 1
if (y) x = 1; // thread 2

由于x和y都不为真,因此另一个值不会设置为true要么。无论指令执行的顺序如何,(正确的)结果始终是x保持为0,y保持为0。

Since neither x nor y is true, the other won't be set to true either. No matter the order the instructions are executed, the (correct) result is always x remains 0, y remains 0.

这篇关于C ++内存模型-此示例是否包含数据竞争?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆