title: Why does my thread not run in background?
body: <p>In the listing bellow, I expect that as I call <code>t.detach()</code> right after the line when the thread is created, the thread <code>t</code> will run in background while the <code>printf("quit the main function now \n")</code> will called and then<code>main</code> will exit.</p>
  
  <pre><code>#include &lt;thread&gt;
  #include &lt;iostream&gt;
  
  void hello3(int* i)
  {
  
      for (int j = 0; j &lt; 100; j++)
      {
          *i = *i + 1;
          printf("From new thread %d \n", *i);
          fflush(stdout);
  
      }
  
      char c = getchar();
   }
  
  int main()
  {
      int i;
      i = 0;
      std::thread t(hello3, &amp;i);
      t.detach();
      printf("quit the main function now \n");
      fflush(stdout);
      return 0;
  }
  </code></pre>
  
  <p>However from what it prints out on the screen it is not the case. It prints</p>
  
  <pre><code>From new thread 1
  From new thread 2
  ....
  From new thread 99
  quit the main function now.
  </code></pre>
  
  <p>It looks like the <code>main</code> function waits until the thread finishes before it executes the command<code>printf("quit the main function now \n");</code> and exits.</p>
  
  <p>Can you please explain why it is? What I am missing here?</p>