title: Is a race condition possible when only one thread writes to a bool variable in c++?
body: <p>In the following code example, program execution never ends.</p>
  
  <p>It creates a thread which waits for a global <code>bool</code> to be set to <code>true</code> before terminating. There is only one writer and one reader. I believe that the only situation that allows the loop to continue running is if the <code>bool</code> variable is false.</p>
  
  <p>How is it possible that the <code>bool</code> variable ends up in an inconsistent state with <em>just one writer</em>?</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;pthread.h&gt;
  #include &lt;unistd.h&gt;
  
  bool done = false;
  
  void * threadfunc1(void *) {
      std::cout &lt;&lt; "t1:start" &lt;&lt; std::endl;
      while(!done);
      std::cout &lt;&lt; "t1:done" &lt;&lt; std::endl;
  
      return NULL;
  }
  
  int main()
  {
      pthread_t threads;
  
      pthread_create(&amp;threads, NULL, threadfunc1, NULL);
  
      sleep(1);
  
      done = true;
      std::cout &lt;&lt; "done set to true" &lt;&lt; std::endl;
  
      pthread_exit(NULL);
  
      return 0;
  }
  </code></pre>