title: Stopping a thread using an `atomic_flag` variable
body: <p>This is related to the second answer to <a href="https://stackoverflow.com/questions/11099601/c-atomic-flag-query-state">this</a> question.</p>
  
  <p>My test code is below. I'm trying to launch a thread, and then to make it stop using the <code>std::atomic_flag</code>. Then the thread should output a number of loop executions and total duration, and stop.</p>
  
  <pre><code>std::atomic_flag keepRunning = ATOMIC_FLAG_INIT;
  
  void F()
  {
    keepRunning.test_and_set();
    long long unsigned count = 0;
    const time_t start = time(nullptr);
    while (keepRunning.test_and_set())
    {
      std::cout &lt;&lt; '.';
      ++count;
    }
    const time_t duration = time(nullptr) - start;
    std::cout &lt;&lt; count &lt;&lt; '\t' &lt;&lt; duration &lt;&lt; std::endl;
  }
  
  int main()
  {
    std::thread t(F);
    keepRunning.clear();
    t.join();
  }
  </code></pre>
  
  <p>The problem is that the thread <strong>doesn't stop</strong>.</p>
  
  <p>Why is that?</p>
  
  <ul>
  <li>Compiler: g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4</li>
  <li>OS: guest OS Ubuntu 14.04 on the macOS Sierra Ver 10.12.2 host</li>
  <li>Compilation flags - I tried <code>-O0</code> and <code>-O4</code>, and it didn't make any difference.</li>
  </ul>