The fact that it works is mostly accidental. If you want to do things like this dependably, you just about need to use some sort of OS-supplied IPC mechanism, possibly with Boost Interprocess (e.g., mutex or semaphore) to give a more portable front end.
volatile
, while often put forward as a solution to problems like this, is neither necessary nor sufficient. It can hurt performance (a lot) but still isn't enough to make threading work correctly. If you're programing for .NET, Microsoft has defined its version of volatile
to provide (at least some degree of) thread safety. Otherwise (in real C or C++), it's of little real use, and can cause considerable harm.
I should also mention that this is a long ways from the first time this mistake has been made. Way back when, no less an authority than Andre Alexandrescu wrote a fairly substantial article in Doctor Dobbs about using volatile
for threading. He's since realized that he was wrong, but (to a large extent) the damage was done -- especially since volatile
is oh so very close to doing the right things that it's extremely easy to mistake it for being right/useful in threading.