스레드 풀을 강조해도 좋습니다. 수백, 수천 개의 작업 항목을 던져서 찢어 버릴 수 있습니다. "굶주림"이 무슨 뜻인지 확실치 않습니다. 우선 순위를 다르게해야하는 일련의 작업 항목이 없으면 기아에 대해 걱정할 필요가 없을 것입니다.
QUWI를 사용하는 경우 병렬화 된 결과를 하나의 단일 결과로 다시 병합하는 방법을 알아내는 것은 사용자의 몫입니다.
지도/축소 접근 방식처럼 나에게 들립니다. 다음은 QUWI를 사용하는 빠른 맵 기능과이를 사용하는 예입니다. 사용
public static IEnumerable<T2> Map_QUWI<T, T2>(List<T> inputs, Func<T, T2> fn)
{
int c = inputs.Count;
if (c == 0) return null;
T2[] result = new T2[c];
if (c == 1)
{
// only one input - perform the work on main thread
result[0] = fn(inputs[0]);
return result;
}
using (ManualResetEvent done = new ManualResetEvent(false))
{
int countdown = inputs.Count;
WaitCallback cb = delegate (Object obj)
{
int ix = (int)obj;
result[ix] = fn(inputs[ix]);
if (Interlocked.Decrement(ref countdown) == 0)
done.Set(); // signal all done
};
// queue up all workitems
for (int i = 0; i < c; i++)
ThreadPool.QueueUserWorkItem(cb,i);
// Wait for done.Set(), which happens in the WaitCallback
// when the last workitem is completed.
done.WaitOne();
}
return result;
}
예 :
// returns the number of prime numbers, less than or equal to x
private int NumberOfPrimesLessThanOrEqualTo(int x)
{
int count= 0;
int n = x;
if (n>=2) count++;
if (x%2==0) n--;
if (n>0)
{
do
{
if (IsPrime(n)) count++;
n-=2;
} while (n>0);
}
return count;
}
private void Demo()
{
var list = new List<int>(new int[] {2,4,8,16,32,64,128,256,512,1024,2048,
4096,8192,16384,32768,65536,131072});
Func<int,int> fn = NumberOfPrimesLessThanOrEqualTo;
var result= Map_QUWI(list, fn);
(new List<int>(result)).ForEach(System.Console.WriteLine);
}