Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 29th, 2012  |  syntax: None  |  size: 0.89 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. C# Multithreading application get its optimum using 16 thread although the computer has 32 cores
  2. int N = 238;
  3.         int P = 16;
  4.  
  5.  
  6.         int Chunk = N / P;
  7.         AutoResetEvent signal = new AutoResetEvent(false);
  8.         // use a counter to reduce
  9.         int counter = P;
  10.  
  11.         // kernel transitions  
  12.         for (int c = 0; c < P; c++)
  13.         {           // for each chunk
  14.             ThreadPool.QueueUserWorkItem(delegate(Object o)
  15.             {
  16.                 int lc = (int)o;
  17.                 for (int i = lc * Chunk; i < (lc + 1 == P ? N : (lc + 1) * Chunk); i++)
  18.                 {
  19.                    // do something
  20.                 }
  21.                 if (Interlocked.Decrement(ref counter) == 0)
  22.                 {
  23.                     signal.Set();
  24.                 }
  25.             }, c);
  26.         }
  27.         signal.WaitOne();
  28.        
  29. Parallel.For(0, N,
  30.     i =>
  31.     {
  32.        // do something
  33.     });