Eksempel:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace E
{
public class Program
{
public static void Main(string[] args)
{
int[] a = Enumerable.Range(1, 1000).ToArray();
DateTime t1, t2;
int sum;
sum = 0;
t1 = DateTime.Now;
foreach(int a1 in a)
{
Thread.Sleep(10); // simulate lots of work
sum += a1;
}
t2 = DateTime.Now;
Console.WriteLine("single thread : result = {0} time = {1}", sum, (t2 - t1).TotalSeconds);
sum = 0;
t1 = DateTime.Now;
Parallel.ForEach(a, (a1) =>
{
Thread.Sleep(10); // simulate lots of work
sum += a1;
});
t2 = DateTime.Now;
Console.WriteLine("multi thread : result = {0} time = {1}", sum, (t2 - t1).TotalSeconds);
sum = 0;
t1 = DateTime.Now;
object mylock = new object();
Parallel.ForEach(a, (a1) =>
{
Thread.Sleep(10); // simulate lots of work
lock(mylock)
{
sum += a1;
}
});
t2 = DateTime.Now;
Console.WriteLine("multi thread synched : result = {0} time = {1}", sum, (t2 - t1).TotalSeconds);
Console.ReadKey();
}
}
}
Output:
single thread : result = 500500 time = 10.005
multi thread : result = 492573 time = 1.5079955
multi thread synched : result = 500500 time = 1.7003891
Det ses at multithreaded er betydeligt hurtigere end singlethreaded.
Men ogsaa at multithreaded uden synkronisering af adgangen til sum giver forkert resultat.