title: C++ multi thread programming with timer
body: <p>I am new to multi thread programming, so this question might seem a little silly, but I really need to work this out so I can apply it to my project (which is way more complicated). 
  Follow is my code, I am trying to have 2 threads (parent and child) to update the same shared timer as they execute and stop when the timer reaches a specific limit. 
  But when I compile and execute this follow piece of code, there are 2 different outcomes: 1. child prints "done by child at 200000" but the program does not exit; 2. after child prints "done by child at 200000" and exits, parent keeps executing, prints a couple of dozen lines of "parent doing work" and "parent at 190000", then prints "done by parent at 200000" and the program exits properly.
  The behavior I want is for whichever thread that updates the timer, hits the limit and exits, the other thread should stop executing and exit as well. I think I might be missing something trivial here, but I've tried changing the code in many ways and nothing I tried seem to work. Any help will be much appreciated :)</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;unistd.h&gt;
  #include &lt;mutex&gt;
  #include &lt;time.h&gt;
  
  using namespace std;
  
  mutex mtx;
  
  int main () {
    int rc;
    volatile int done = 0;
    clock_t start = clock();
    volatile clock_t now;
  
    rc = fork();
    if (rc == 0) { //child
      while (true) {
        cout &lt;&lt; "child doing work" &lt;&lt; endl;
        mtx.lock();
        now = clock() - start;
        if (done) {
          mtx.unlock();
          break;
        }
        if (now &gt;= 200000 &amp;&amp; !done) {
          done = 1;
          cout &lt;&lt; "done by child at " &lt;&lt; now &lt;&lt; endl;
          mtx.unlock();
          break;
        }
        cout &lt;&lt; "child at " &lt;&lt; now &lt;&lt; endl;
        mtx.unlock();
      }
      _exit(0);
    }
    else { // parent
      while (true) {
        cout &lt;&lt; "parent doing work" &lt;&lt; endl;
        mtx.lock();
        now = clock() - start;
        if (done) {
          mtx.unlock();
          break;
        }
        if (now &gt;= 200000 &amp;&amp; !done) {
          done = 1;
          cout &lt;&lt; "done by parent at " &lt;&lt; now &lt;&lt; endl;
          mtx.unlock();
          break;
        }
        cout &lt;&lt; "parent at " &lt;&lt; now &lt;&lt; endl;
        mtx.unlock();
      }
    }
    return 0;
  }
  </code></pre>