You use volatile on global or static variables that may be used by more than 1 thread. It does not make sense to use on local variables, because these cannot be used by more than 1 thread. (actually, you could construct cases where that would not be true, but that would be very very unusual, so you can use it on locals, but I really doubt it woudl ever be needed.) It insures that the compiler does not optimize the code in some way so that changes made to the variable by one thread are not detected by other threads. (basically it insures that the compiler does not "cache" the variable in a register even under conditions where it seems safe to do so.)

By itself "volatile" is usually not enough to insure that a variable may be safely accessed by multiple threads. You will often also need a synchronization mechanism, like a mutex, to insure that only one thread access the variable at a time. (The mutex insures that one thread uses the variable at a time and the "volatile" insures that the thread really accesses it, rather than a cached copy.)

Written by John Humphreys
C++ Threading and the POSIX Library
This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.
[s…

Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …