title: How to program number of your threads in Delphi
body: <p>I found this on the Dr Dobbs site today at 
  <a href="http://www.ddj.com/hpc-high-performance-computing/220300055?pgno=3" rel="nofollow noreferrer">http://www.ddj.com/hpc-high-performance-computing/220300055?pgno=3</a>
  It's a nice suggestion regarding thread implmentation.
  What is best way of achieving this with TThread in Delphi I wonder?
  Thanks
  Brian</p>
  
  <p>=== From Dr Dobbs ==============</p>
  
  <p>Make multithreading configurable! The number of threads used in a program should always be configurable from 0 (no additional threads at all) to an arbitrary number. This not only allows a customization for optimal performance, but it also proves to be a good debugging tool and sometimes a lifesaver when unknown race conditions occur on client systems. I remember more than one situation where customers were able to overcome fatal bugs by switching off multithreading. This of course does not only apply to multithreaded file I/O. </p>
  
  <p>Consider the following pseudocode: </p>
  
  <pre><code>int CMyThreadManger::AddThread(CThreadObj theTask)
  {
      if(mUsedThreadCount &gt;= gConfiguration.MaxThreadCount())
          return theTask.Execute(); // execute task in main thread
      // add task to thread pool and start the thread
      ...
  }
  </code></pre>
  
  <p>Such a mechanism is not very complicated (though a little bit more work will probably be needed than shown here), but it sometimes is very effective. It also may be used with prebuilt threading libraries such as OpenMP or Intel's Threaded Building Blocks. Considering the measurements shown here, its a good idea to include more than one configurable thread count (for example, one for file I/O and one for core CPU tasks). The default might probably be 0 for file I/O and &lt;<em>number of cores found</em>&gt; for CPU tasks. But all multithreading should be detachable. A more sophisticated approach might even include some code to test multithreaded performance and set the number of threads used automatically, may be even individually for different tasks. </p>
  
  <p>===================</p>