4 ms·
> The optimizer may reorder or remove memory accesses in ways that wouldn't happen on the target hardware. yes, but so far (C/C++2003) I always thought that
by jackewiehose 6y ago
> The optimizer may reorder or remove memory accesses in ways
that wouldn't happen on the target hardware.
yes, but so far (C/C++2003) I always thought that something like
mutex.lock() in the example, before accessing x, would be recognized
as a memory barrier by the optimizer so it should be safe to access x
as long as your thread acquired the lock.
Now for C++11 I'm not so sure anymore because of this last paragraph of
the article:
> What’s more, since C++11 has well defined memory semantics, compiler
writers are no longer forced to be conservative with their
optimizations. If the programmer doesn’t specifically mark shared
variables as atomic, the compiler is free to optimize code as if it
were single-threaded.
Does this really mean that the above x must always be declared
volatile even though it's surrounded by a mutex-lock? If so I hope
there's a compiler flag do get the old behavior...
- secondcoming 6y agoIn this instance the shared variable isn't x, but the internal workings of the mutex.
- manwe150 6y agoA mutex lock will still be modeled as an aliasing read/write of all global memory. So you’re fine.
- kccqzy 6y agoNo, you shouldn't declare x as volatile. Also note that the article never even talked about volatile in C++; volatile in C++ is entirely different from volatile in Java. Instead when you use a mutex, your mutex internally uses atomics. In fact the simplest kind of mutex can be built with atomics alone (spinlock), though a production-quality mutex will have to use other techniques such as a Linux futex.