123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading;
- namespace Utilities
- {
- public delegate void ForDelegate(int i);
- public delegate void DelegateProcess();
-
-
-
-
- public class Parallel
- {
-
-
-
-
-
- public static void For(int fromInclusive, int toExclusive, ForDelegate forDelegate)
- {
- int chunkSize = 4;
- For(fromInclusive, toExclusive, chunkSize, forDelegate);
- }
-
-
-
-
-
-
-
-
-
-
- public static void For(int fromInclusive, int toExclusive, int chunkSize, ForDelegate forDelegate)
- {
- int threadCount = Environment.ProcessorCount;
- For(fromInclusive, toExclusive, chunkSize, threadCount, forDelegate);
- }
-
-
-
-
-
-
-
-
-
-
-
- public static void For(int fromInclusive, int toExclusive, int chunkSize, int threadCount, ForDelegate forDelegate)
- {
- int index = fromInclusive - chunkSize;
-
- object locker = new object();
-
-
- DelegateProcess process = delegate()
- {
- while (true)
- {
- int chunkStart = 0;
- lock (locker)
- {
-
- index += chunkSize;
- chunkStart = index;
- }
-
-
-
- for (int i = chunkStart; i < chunkStart + chunkSize; i++)
- {
- if (i >= toExclusive) return;
- forDelegate(i);
- }
- }
- };
-
- IAsyncResult[] asyncResults = new IAsyncResult[threadCount];
- for (int i = 0; i < threadCount; ++i)
- {
- asyncResults[i] = process.BeginInvoke(null, null);
- }
-
- for (int i = 0; i < threadCount; ++i)
- {
- process.EndInvoke(asyncResults[i]);
- }
- }
- }
- }
|