I’ve been reading from many sources that the volatile keyword is not helpful in multithreaded scenarios. However, this assertion is constantly challenged by atomic operation functions that accept volatile pointers.
For instance, on Mac OS X, we have the OSAtomic function family:
SInt32 OSIncrementAtomic(volatile SInt32 *address);
SInt32 OSDrecrementAtomic(volatile SInt32 *address);
SInt32 OSAddAtomic(SInt32 amount, volatile SInt32 *address);
// ...
And it seems that there is a similar usage of the volatile keyword on Windows for Interlocked operations:
LONG __cdecl InterlockedIncrement(__inout LONG volatile *Addend);
LONG __cdecl InterlockedDecrement(__inout LONG volatile *Addend);
It also seems that in C++11, atomic types have methods with the volatile modifier, which must somehow mean that the volatile keyword has some kind of relationship with atomicity.
So, what am I missing? Why do OS vendors and standard library designers insist on using the volatile keyword for threading purposes if it’s not useful?
It suddenly came to me that I simply misinterpreted the meaning of
volatile*. Much likeconst*means the pointee shouldn’t change,volatile*means that the pointee shouldn’t be cached in a register. This is an additional constraint that can be freely added: as much as you can cast achar*to aconst char*, you can cast anint*to avolatile int*.So applying the
volatilemodifier to the pointees simply ensures that atomic functions can be used on alreadyvolatilevariables. For non-volatile variables, adding the qualifier is free. My mistake was to interpret the presence of the keyword in the prototypes as an incentive to use it rather than as a convenience to those using it.