Consider this function:
void foo(int * p)
{
// something
}
Can the compiler assume that no other thread will modify the value pointed by p? Or does it have to act as if this value can be modified any moment?
void bar(volatile int * p)
{
}
If it does not, does the volatile
keyword helps? GOTW #69 states that volatile
keyword is mostly always ignored by compilers.
EDIT: Apparently there is some misunderstanding on the phrase “the compiler assumes”. Let me clarify this:
- If the compiler assumes so, it can put the value of
*p
in a register the first time it is read, then use it until p goes out of scope. At that moment, it should write the value of*p
at that memory address. - If the compiler does NOT assume so, every time
*p
is read, the compiler should fetch its value from memory as there is a chance some other thread modified it. Every time*p
is changed, the compiler should write it to memory so that other threads can read it