c#,parallel,for,sample

Kerim 8/7/2016 0

my parallel for sample method

C#
 public static void MyParallelFor(
 int inclusiveLowerBound, int exclusiveUpperBound, Action <int> body)
        {
            // Get the number of processors, initialize the number of remaining
            // threads, and set the starting point for the iteration.
            int numProcs = Environment .ProcessorCount;
            int remainingWorkItems = numProcs;
            int nextIteration = inclusiveLowerBound;
            const int batchSize = 3;
            using (ManualResetEvent mre = new ManualResetEvent(false ))
            {
                // Create each of the work items.
                for (int p = 0; p < numProcs; p  )
                {
                    ThreadPool.QueueUserWorkItem(delegate
                                                     {
                                                         int index;
                                                         while ((index = Interlocked.Add(
                                                             ref nextIteration, batchSize) - batchSize)
                                                                < exclusiveUpperBound)
                                                         {
                                                             // In a real implementation, we’d need to handle
                                                             // overflow on this arithmetic.
                                                             int end = index   batchSize;
                                                             if (end >= exclusiveUpperBound) end = exclusiveUpperBound;
                                                             for (int i = index; i < end; i  ) body(i);
                                                         }
                                                         if (Interlocked.Decrement(ref remainingWorkItems) == 0)
                                                             mre.Set();
                                                     });
                }
                // Wait for all threads to complete
                mre.WaitOne();
            }
        }

 

Report Bug

Please Login to Report Bug

Reported Bugs

Comments

Please Login to Comment

Comments