title: Multithread for loop function not working correctly
body: <p>I tried to implement simple for loop running on custom number of threads like this:</p>
  <pre><code>#include &lt;thread&gt;
  
  template&lt;typename func, typename... args&gt;
  void threadFor(int numOfThreads, int repeats, func f, args... a)
  {
      auto forPart = [&amp;](int repeats){
          for (int i = 0; i &lt; repeats; ++i) f(i, a...);
      };
      
      int part      = repeats / numOfThreads;
      int remainder = repeats % numOfThreads;
  
      std::thread threads[numOfThreads];
  
      for (int i = 0; i &lt; numOfThreads; ++i)
      {
          threads[i] = std::thread(forPart,part + (i &lt; remainder));
      }
  
      for (int i = 0; i &lt; numOfThreads; ++i) threads[i].join();
  }
  </code></pre>
  <p>I am testing it in the following way:</p>
  <pre><code>#include &lt;iostream&gt;
  
  void increment(int i, int* j){++*j;}
  
  int main()
  {
      int j = 0;
      threadFor(8,1000000, increment, &amp;j);
  
      std::cout &lt;&lt; j;
  }
  </code></pre>
  <p>When I execute the code, j is less than 1,000,000. Also, the code sometimes crushes because of double deletion or segmentation error. What am I doing wrong?</p>