In C/C++, are volatile variables guaranteed to have eventually consistent semantics betwen threads? In C/C++, are volatile variables guaranteed to have eventually consistent semantics betwen threads? multithreading multithreading

In C/C++, are volatile variables guaranteed to have eventually consistent semantics betwen threads?


It's going to depend on your architecture. While it is unusual to require an explicit cache flush or memory sync to ensure memory writes are visible to other threads, nothing precludes it, and I've certainly encountered platforms (including the PowerPC-based device I am currently developing for) where explicit instructions have to be executed to ensure state is flushed.

Note that thread synchronisation primitives like mutexes will perform the necessary work as required, but you don't typically actually need a thread synchronisation primitive if all you want is to ensure the state is visible without caring about consistency - just the sync / flush instruction will suffice.

EDIT: To anyone still in confustion about the volatile keyword - volatile guarantees the compiler will not generate code that explicitly caches data in registers, but this is NOT the same thing as dealing with hardware that transparently caches / reorders reads and writes. Read e.g. this or this, or this Dr Dobbs article, or the answer to this SO question, or just pick your favourite compiler that targets a weakly consistent memory architecture like Cell, write some test code and compare what the compiler generates to what you'd need in order to ensure writes are visible to other processes.


If I've understood correctly the relevant sections, C++0X won't guaranteed it for standalone variable or even volatile one (volatile isn't designed for that use), but will introduce atomic types for which you'll have the guarantee (see header <atomic>).


First off, if it's not marked volatile there is a good chance the compiler may only load it once. So regardless of whether the memory eventually changes, there is no guarantee the compile will set it.

Since you explicitly say "no mutexes", pthreads doesn't apply.

Beyond that, since C++ does not have a memory model, it depends on the hardware architecture.