// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Threading; namespace Basic { public class Program { public class Data { public string S { get; set; } } public class Processor { private Data d; public Processor(Data d) { this.d = d; } public void Run() { // simulate a lot of work that takes 0.1 second string s = d.S; Thread.Sleep(100); d.S = s + "X"; } } public static void Test(int njobs, int nthreads) { // setup data Data[] d = new Data[njobs]; for(int i = 0; i < njobs; i++) { d[i] = new Data { S = "X" }; } // process DateTime dt1 = DateTime.Now; int k = 0; for(int i = 0; i < njobs / nthreads; i++) { // create threads Thread[] t = new Thread[nthreads]; for(int j = 0; j < nthreads; j++) { t[j] = new Thread((new Processor(d[k])).Run); k++; } // start threads for(int j = 0; j < nthreads; j++) { t[j].Start(); } // wait for threads to complete for(int j = 0; j < nthreads; j++) { t[j].Join(); } } DateTime dt2 = DateTime.Now; Console.WriteLine("{0} jobs executing in {1} threads : {2:F1} seconds", njobs, nthreads, (dt2 - dt1).TotalSeconds); // check data for(int i = 0; i < njobs; i++) { if(d[i].S != "XX") Console.WriteLine("Ooops"); } } public static void Main(string[] args) { Test(256, 1); Test(256, 2); Test(256, 4); Test(256, 8); Test(256, 16); Test(256, 32); Test(256, 64); Console.ReadKey(); } } }