title: Condition variable basic example
body: <p>I am learning condition variables in C++11 and wrote this program based on a sample code.</p>
  
  <p>The goal is to accumulate in a vector the first ten natural integers that are generated by a producer and pushed into the vector by a consumer. However it does not work since, for example on some runs, the vector only contains 1, 7 and 10.</p>
  
  <pre><code>#include &lt;mutex&gt;
  #include &lt;condition_variable&gt;
  #include&lt;vector&gt;
  #include &lt;iostream&gt;
  #include &lt;cstdio&gt;
  
  std::mutex mut;
  #define MAX     10
  int counter;
  bool isIncremented = false;
  std::vector&lt;int&gt; vec;
  std::condition_variable condvar;
  
  void producer() {
      while (counter &lt; MAX) {
          std::lock_guard&lt;std::mutex&gt; lg(mut);
          ++counter;
          isIncremented = true;
          condvar.notify_one();
      }
  }
  
  void consumer() {
      while (true) {
          std::unique_lock&lt;std::mutex&gt; ul(mut);
          condvar.wait(ul, [] { return isIncremented; });
          vec.push_back(counter);
          isIncremented = false;
          if (counter &gt;= MAX) {
              break;
          }
      }
  }
  
  int main(int argc, char *argv[]) {
      std::thread t1(consumer);
      std::thread t2(producer);
      t2.join();
      t1.join();
  
      for (auto i : vec) {
          std::cout &lt;&lt; i &lt;&lt; ", ";
      }
      std::cout &lt;&lt; std::endl;
      // Expected output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
      // Example of actual output: 1, 7, 10,
  
      std::cout &lt;&lt; "Press enter to quit";
      getchar();
      return 0;
  }
  </code></pre>