title: C++ Wait in main thread for future without while(true)
body: <h2>Question</h2>
  <p>I want to know if it is possible to wait in the main-Thread without any while(1)-loop.
  I launch a few threads via <code>std::async()</code> and do calculation of numbers on each thread. After i start the threads i want to receive the results back. I do that with a <code>std::future&lt;&gt;.get()</code>.</p>
  <h2>My problem</h2>
  <p>When i receive the result i call <code>std::future.get()</code>, which blocks the main thread until the calculation on the thread is done. This leads to some slower execution time, if one thread needs considerably more time then the following, where i could do some calculation with the finished results instead and then when the slowest thread is done i maybe have some some further calculation.</p>
  <p>Is there a way to idle the main thread until ANY of the threads has finished running? I have thought of a callback function which wakes the main thread up, but i still don't know how to idle the main function without making it unresponsive for i.e. a second and not running a while(true) loop instead.</p>
  <h2>Current code</h2>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;future&gt;
  
  uint64_t calc_factorial(int start, int number);
  
  int main()
  {
      uint64_t n = 1;
  
      //The user entered number 
      uint64_t number = 0;
  
      // get the user input
      printf(&quot;Enter number (uint64_t): &quot;);
      scanf(&quot;%lu&quot;, &amp;number);
  
      std::future&lt;uint64_t&gt; results[4];
      for (int i = 0; i &lt; 4; i++)
      {
          // push to different cores
          results[i] = std::async(std::launch::async, calc_factorial, i + 2, number);
      }
  
      for (int i = 0; i &lt; 4; i++)
      {
          //retrieve result...I don't want to wait here if one threads needs more time than usual
          n *= results[i].get();
      }
      // print n or the time needed 
      return 0;
  }
  </code></pre>
  <pre><code>uint64_t calc_factorial(int start, int number)
  {
      uint64_t n = 1;
      for (int i = start; i &lt;= number; i+=4) n *= i;
      return n;
  }
  </code></pre>
  <p>I prepared a code snippet which runs fine, I am using the <a href="https://gmplib.org/" rel="nofollow noreferrer">GMP Lib</a> for the big results, but the code runs with <code>uint64_t</code> instead if you enter small numbers.</p>
  <h3>Note</h3>
  <p>If you have compiled the GMP library for whatever reason on your PC already you could replace every <code>uint64_t</code> with <code>mpz_class</code></p>