I’m aware of the use of volatile in Java.
That is (based on the wikipedia article):
There is a global ordering on the reads and writes to a volatile
variable. This implies that every thread accessing a volatile field
will read its current value before continuing, instead of
(potentially) using a cached value.
I also I’m aware that there exists the volatile keyword in C but in a quite different context, mainly to be used in memory-mapped I/O.
So I was wondering, is there some construct like Java’s volatile in C? Which will prevent
reading cached values of a variable?
If it doesn’t exist in C, is there perhaps a library with such a construct, like pthread?
volatilein C is basically an anachronism that was intended for a completely different scenario and is NOT useful for multi threaded programming. For some reasons or another even the newest c++ standard couldn’t give it more meaning but had to invent a new keyword instead.Mind you this means
volatileas defined by the C standard is useless, compilers may give you additional guarantees (I know that MS VC does and I think it gives basically the same guarantees as does volatile in java) but that means the program is locked to that one compiler. Most compilers also have some intrinsics to insert memory barriers, which is a bit more explicit but again not portable per se.In practice you’re probably best of using some higher level threading library that offers the right tools for the job. E.g. POSIX gives you low level memory barriers afaik.
On the c++ site it’s better since 0x11 – the standard does offer
std::atomic_thread_fenceand atomic variables. Note though that the c++0x11 memory model is NOT identical to the java one, so you’ll have to be careful when porting.