As a result of my answer to this question, I started reading about the keyword volatile
and what the consensus is regarding it. I see there is a lot of informat
There are three major problems you are facing when multithreading:
1) Synchronization and thread safety. Variables that are shared between several threads must be protected from being written to by several threads at once, and prevented from being read during non-atomic writes. Synchronization of objects can only be done through a special semaphore/mutex object which is guaranteed to be atomic by itself. The volatile keyword does not help.
2) Instruction piping. A CPU can change the order in which some instructions are executed to make code run faster. In a multi-CPU environment where one thread is executed per CPU, the CPUs pipe instructions without knowing that another CPU in the system is doing the same. Protection against instruction piping is called memory barriers. It is all explained well at Wikipedia. Memory barriers may be implemented either through dedicated memory barrier objects or through the semaphore/mutex object in the system. A compiler could possibly chose to invoke a memory barrier in the code when the volatile keyword is used, but that would be rather special exception and not the norm. I would never assume that the volatile keyword did this without having it verified in the compiler manual.
3) Compiler unawareness of callback functions. Just as for hardware interrupts, some compilers may not know that an callback function has been executed and updated a value in the middle of code execution. You can have code like this:
// main
x=true;
while(something)
{
if(x==true)
{
do_something();
}
else
{
do_seomthing_else();
/* The code may never go here: the compiler doesn't realize that x
was changed by the callback. Or worse, the compiler's optimizer
could decide to entirely remove this section from the program, as
it thinks that x could never be false when the program comes here. */
}
}
// thread callback function:
void thread (void)
{
x=false;
}
Note that this problem only appears on some compilers, depending on their optimizer settings. This particular problem is solved by the volatile keyword.
So the answer to the question is: in a multi-threaded program, the volatile keyword does not help with thread synchronization/safety, it does likely not act as a memory barrier, but it could prevent against dangerous assumptions by the compiler's optimizer.