title: Safe to use volatile bool to force another thread to wait? (C++)
body: <p>Everything I've read about volatile says it's never safe, but I still feel inclined to try it, and I haven't seen this specific scenario declared unsafe.</p>
  
  <p>I have a separate thread that renders a scene, pulling data from the main simulation thread.  This has no synchronization, and works fine.</p>
  
  <p>The issue is that when the program exits, then renderer needs to stop pulling data from the simulation thread before the simulation thread can safely clean itself up without causing the renderer to attempt reading invalid memory.</p>
  
  <p>To accomplish this, I have the renderer run infinitely in its thread:</p>
  
  <pre><code>volatile bool stillRendering;
  
  void RenderThreadFunction()
  {
      stillRendering = true;
  
      while(programRunning)
      {
          renderer-&gt;render();
      }
  
      stillRendering = false;
  }
  </code></pre>
  
  <p>In the main program thread, when the windproc quit message is received, I do:</p>
  
  <pre><code>void OnQuit()
  {
      programRunning = false;
      while(stillRendering)
      {
      }
  
      delete application;
  }
  </code></pre>
  
  <p>The goal of this is to be sure the renderer stops pulling data from the application before calling delete on the application.</p>
  
  <p>I first tried this without any volatile keywords, and it worked in debug mode, but in release mode it hung.  I assume the compiler made some optimization that causes the program to stop checking the value of stillRendering.</p>
  
  <p>Adding volatile to just stillRendering caused the application to successfully exit everytime I've tested it so far.  I'm not certain why it doesn't seem to matter if "programRunning" is volatile.</p>
  
  <p>Lastly, I am uncertain how the performance of the program will be impacted by using volatile for "stillRendering".  It doesn't matter to me if making stillRendering volatile affects the performance of OnQuit(), but it does matter to me if it affects the performance of RenderThreadFunction()</p>