// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Threading; namespace E { public interface Traditional { void Incr(ThreadSafeTest subj); } public class TraditionalSafe : Traditional { public void Incr(ThreadSafeTest subj) { lock(subj) { subj.N = subj.N + 1; } } } public class TraditionalUnsafe : Traditional { public void Incr(ThreadSafeTest subj) { subj.N = subj.N + 1; } } public delegate void Lambda(ThreadSafeTest subj); public class ThreadSafeTestThread { private Traditional o; private Lambda del; private ThreadSafeTest subj; private int nit; public ThreadSafeTestThread(Traditional o, Lambda del, ThreadSafeTest subj, int nit) { this.o = o; this.del = del; this.subj = subj; this.nit = nit; } public void Run() { for(int i = 0; i < nit; i++) { if(o != null) { o.Incr(subj); } else if(del != null) { del(subj); } } } } public class ThreadSafeTest { public int N { get; set; } public void Test(Traditional o, Lambda del) { N = 0; Thread[] t = new Thread[8]; for(int i = 0; i < t.Length; i++) { t[i] = new Thread((new ThreadSafeTestThread(o, del, this, 1000000)).Run); } for(int i = 0; i < t.Length; i++) { t[i].Start(); } for(int i = 0; i < t.Length; i++) { t[i].Join(); } Console.WriteLine(N); } } public class Program { public static void Main(string[] args) { ThreadSafeTest tst = new ThreadSafeTest(); tst.Test(new TraditionalUnsafe(), null); tst.Test(new TraditionalSafe(), null); tst.Test(null, (subj) => subj.N = subj.N + 1); tst.Test(null, (subj) => { lock(subj) { subj.N = subj.N + 1; } }); } } }