title: Basic timer with std::thread and std::chrono
body: <p>I'm trying to implement a basic timer with the classic methods: start() and stop(). I'm using c++11 with std::thread and std::chrono.</p>
  
  <ul>
  <li>Start method. Creates a new thread that is asleep for a given interval time, then execute a given std::function. This process is repeated while a 'running' flag is true.</li>
  <li>Stop method. Just sets the 'running' flag to false.</li>
  </ul>
  
  <p>I created and started a Timer object that show "Hello!" every second, then with other thread I try to stop the timer but I can't. The Timer never stops.</p>
  
  <p>I think the problem is with th.join()[*] that stops execution until the thread has finished, but when I remove th.join() line obviously the program finishes before the timer start to count.</p>
  
  <p>So, my question is how to run a thread without stop other threads?</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;thread&gt;
  #include &lt;chrono&gt;
  
  using namespace std;
  
  class Timer
  {
      thread th;
      bool running = false;
  
  public:
      typedef std::chrono::milliseconds Interval;
      typedef std::function&lt;void(void)&gt; Timeout;
  
      void start(const Interval &amp;interval,
                 const Timeout &amp;timeout)
      {
          running = true;
  
          th = thread([=]()
          {
              while (running == true) {
                  this_thread::sleep_for(interval);
                  timeout();
              }
          });
  
  // [*]
          th.join();
      }
  
      void stop()
      {
          running = false;
      }
  };
  
  int main(void)
  {
      Timer tHello;
      tHello.start(chrono::milliseconds(1000),
                   []()
      {
          cout &lt;&lt; "Hello!" &lt;&lt; endl;
      });
  
      thread th([&amp;]()
      {
          this_thread::sleep_for(chrono::seconds(2));
          tHello.stop();
      });
  
      th.join();
  
      return 0;
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>Hello!
  Hello!
  ...
  ...
  ...
  Hello!
  </code></pre>