title: C++ 11 - condition_variable - wait_until not working as expected
body: <p>I have implemented a sample program to understand how wait_for and wait_until works in C++11.</p>
  
  <p>Code - </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;future&gt;
  #include &lt;chrono&gt;
  #include &lt;mutex&gt;
  #include &lt;condition_variable&gt;
  #include &lt;thread&gt;
  
  using namespace std;
  using namespace std::chrono;
  
  condition_variable cv;
  mutex m;
  bool flagValue=false;
  
  int sampleFunction(int a)
  {
      cout&lt;&lt;"Executing sampleFunction...";
      cout.flush();
      this_thread::sleep_for(seconds(5));
      cout&lt;&lt;"Done."&lt;&lt;endl;
      return a;
  }
  
  void sampleFunctionCond(int a)
  {
      lock_guard&lt;mutex&gt; lg(m);
      cout&lt;&lt;"Executing sampleFunctionCond...";
      cout.flush();
      this_thread::sleep_for(seconds(5));
      cout&lt;&lt;"Done."&lt;&lt;endl;
      cout&lt;&lt;"Value : "&lt;&lt;a&lt;&lt;endl;
      flagValue=true;
      cv.notify_one();
      return;
  }
  
  int main()
  {
     unique_lock&lt;mutex&gt; ul(m);
     future&lt;int&gt; f1=async(launch::async,sampleFunction,10);
     future_status statusF1=f1.wait_for(seconds(1));
     if(statusF1==future_status::ready)
      cout&lt;&lt;"Future is ready"&lt;&lt;endl;
     else if (statusF1==future_status::timeout)
      cout&lt;&lt;"Timeout occurred"&lt;&lt;endl;
     else if (statusF1==future_status::deferred)
      cout&lt;&lt;"Task is deferred"&lt;&lt;endl;
     cout&lt;&lt;"Value : "&lt;&lt;f1.get()&lt;&lt;endl;
  
     cv_status statusF2;
     thread t1(sampleFunctionCond,20);
     t1.detach();
     while(!flagValue)
     {
         statusF2=cv.wait_until(ul,system_clock::now()+seconds(2));
         if(statusF2==cv_status::timeout)
         {
         cout&lt;&lt;"Timeout occurred."&lt;&lt;endl;
         break;
         }
         else
         {
         cout&lt;&lt;"Condition variable is ready or spurious wake up occurred."&lt;&lt;endl;
         }
     }
  }
  </code></pre>
  
  <p>Output - </p>
  
  <pre><code>Executing sampleFunction...Timeout occurred
  Done.
  Value : 10
  Executing sampleFunctionCond...Done.
  Value : 20
  Timeout occurred.
  </code></pre>
  
  <p>sampleFunction is working as expected as its printing "Timeout occurred" before "Done" but same is not the case with sampleFunctionCond. Though it knows wait_until has timed out but its printing the message after the function sampleFunctionCOnd has finished executing.</p>
  
  <p>Can someone please help me understand this? Thanks.</p>