Search code examples
c++multithreadingc++11storage-duration

Static storage objects optimization on thread context


Can a compiler optimize a static storage object in multithread program context? I'm asking it to know if a variable declared as static, for instance, generates a side effect when used in a function called in a thread.

bool flag = false; // static storage duration object

void f(){ //function called in a thread
  flag = false;
  // do some work...
  flag = true;
}

//a possible representation of the code above after optimization
void f(){
  flag = true;
  // do some work...
} // is this possible to happen?

I read some answers from here, but I didn't find anything that could help.


Solution

  • Static storage duration has no affect on thread safety. In your example the second code block would be legal as long as the reordering doesn't break anything inside f.

    You still need synchronization on all shared objects that any thread writes to. In this case you could get that by using a std::atomic<bool> for flag like

    std::atomic<bool> flag = false;
    

    The rule for thread safety is that if you have an object shared between multiple threads, and at least one of them is a writer, then you need synchronization. If you do not then you have a data race which is undefined behavior.