title: How to set number of threads in C++
body: <p>I have written the following multi-threaded program for multi-threaded sorting using std::sort. In my program grainSize is a parameter. Since grainSize or the number of threads which can spawn is a system dependent feature. Therefore, I am not getting what should be the optimal value to which I should set the grainSize to? I work on Linux?</p>
  
  <pre><code> int compare(const char*,const char*)
  {
     //some complex user defined logic    
  }
  void multThreadedSort(vector&lt;unsigned&gt;::iterator data, int len, int grainsize)
  {
      if(len &lt; grainsize) 
      {
          std::sort(data, data + len, compare);
      }
      else
      {
          auto future = std::async(multThreadedSort, data, len/2, grainsize);
  
          multThreadedSort(data + len/2, len/2, grainsize); // No need to spawn another thread just to block the calling thread which would do nothing.
  
          future.wait();
  
          std::inplace_merge(data, data + len/2, data + len, compare);
      }
  }
  
  int main(int argc, char** argv) {
  
      vector&lt;unsigned&gt; items;
      int grainSize=10;
      multThreadedSort(items.begin(),items.size(),grainSize);
      std::sort(items.begin(),items.end(),CompareSorter(compare));
      return 0;
  }
  </code></pre>
  
  <p>I need to perform multi-threaded sorting. So, that for sorting large vectors I can take advantage of multiple cores present in today's processor. If anyone is aware of an efficient algorithm then please do share.</p>
  
  <p>I dont know why the value returned by multiThreadedSort() is not sorted, do you see some logical error in it, then please let me know about the same</p>