简体   繁体   中英

Success of write with simultaneous read

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
}

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

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.

In practice nothing probably will fail. However, the C++11/14 standard is pretty clear in this regard. Here is a quote from C++14 draft section [intro.multithread]/23 (emphasis mine):

The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other, except for the special case for signal handlers described below. Any such data race results in undefined behavior.

Where conflicting actions are defined at [intro.multithread]/6 :

Two expression evaluations conflict if one of them modifies a memory location (1.7) and the other one accesses or modifies the same memory location.

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM