写同时读取的成功 [英] Success of write with simultaneous read

查看:122
本文介绍了写同时读取的成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果程序中的一个线程试图从另一个变量读取变量,读取的值当然是未定义的。然而,假设只有一个作家,写保证成功?例如:

If one thread in a program attempts to read from a variable while another writes to it, the value read is of course undefined. However, assuming there is only one writer, is the write guaranteed to succeed? For example:

bool myGlobalVariable = false;
void thread1() {
    myGlobalVariable = true;
}
void thread2() {
    bool x = myGlobalVariable; //x is undefined
}

在这种情况下, myGlobalVariable 保证为 true

In this case, once both threads are finished, is myGlobalVariable guaranteed to be true?

我特别想知道gcc on linux,但我很想知道其他操作系统和编译器是做什么的,或者如果ARM的行为不同于x86。 / p>

I'm specifically wondering about gcc on linux, but I'd be interested to know what other operating systems and compilers do, or if ARM behaves differently than x86.

推荐答案

我看不到这可能无法在任何情况下写入值,如果它只是一个写而不是读取。

I can't see how this could possibly fail to write the value under any circumstances, if it's just a write and not a read.

多线程访问同一个变量的危险的原因正是有没有检查是否对变量进行检查在操作期间修改。

The reason that multithreaded access to the same variable is dangerous is precisely that there's no checking being done as to whether the variable is being modified during an operation. It's not that it might check and then complain.

因此,在单个写入的情况下,只是一个写入(因此没有 i ++ ,这也是一个读),它必须成功。

So in the case of a single write, and just a write (so no i++, which is a read as well), it must succeed.

当然,你可以设计硬件,如果你想失败,没有看到任何标准架构可能失败。

Of course, you could design hardware that would fail if you wanted to, but I don't see how any standard architecture could fail.

正如Anton在他的回答中指出的,规范说它是未定义的行为,因此可以写一个有效的C ++编译器,故意监视这种行为并随机化结果。但是没有编译器会在实践中这样做。

As Anton points out in his answer, the spec says it's undefined behaviour, and so it would be possible to write a valid C++ compiler that deliberately watches out for such behaviour and randomises the result. But no compiler is going to do that in practice.

这就是说,依赖于正式未定义的行为是一个好主意,所以jeffamaphone的评论说,你的问题的正确答案是,写作将成功,但你仍然不应该这样做。

That said, it's never a good idea to rely on behaviour that's officially undefined, so as the comment from jeffamaphone says, the right answer to your question is that the write will succeed, but you still shouldn't do it.

这篇关于写同时读取的成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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