// 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 NotCorrect { 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 some work between get and set string s = d.S; Thread.Yield(); d.S = s + "X"; } } public static void Test(int njobs, int nthreads) { // setup data Data d = new Data { S = "" }; // process with shared data 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)).Run); } // 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(); } } Console.WriteLine("{0} threads : expected = {1}, actual = {2}", nthreads, njobs, d.S.Length); } public static void Main(string[] args) { Test(2560, 1); Test(2560, 2); Test(2560, 4); Test(2560, 8); Test(2560, 16); Test(2560, 32); Test(2560, 64); Console.ReadKey(); } } }