static void Main(string[] args)輸出的結果為:
{
Listlist = new List ();
int result = 0;
Parallel.For(1, 11, i =>
{
System.Console.WriteLine("I'm " + i);
System.Console.WriteLine("I'm in thread " + Thread.CurrentThread.ManagedThreadId);
list.Add(T(i));
result += T(i);
Thread.Sleep(2000);
});
Console.WriteLine(list.Sum());
Console.WriteLine(result);
Console.ReadLine();
}
static int T(int input)
{
int result = 1;
for (int i = 1; i <= input; i++)
{
result *= i;
}
return result;
}
I'm 1
I'm 2
I'm in thread 4
I'm in thread 1
I'm 6
I'm in thread 3
I'm 7
I'm in thread 5
I'm 3
I'm in thread 1
I'm 8
I'm in thread 3
I'm 10
I'm in thread 6
I'm 5
I'm in thread 4
I'm 4
I'm in thread 1
I'm 9
I'm in thread 3
4037913
4037913
從thread的id我們可以看出他一共開了5個thread來從處理。
而且list與result這兩個物件的thread safe他都幫我們做掉了
平行運算就是這麼簡單
沒有留言:
張貼留言