// 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; public class MultiSemaphore { public const int EXCLUSIVE = 1; public const int SHARED = 2; private int nouser; private int mode; public MultiSemaphore() { nouser = 0; } public void Get(int mode) { lock(this) { while ((this.mode == EXCLUSIVE || mode == EXCLUSIVE) && nouser > 0) { Monitor.Wait(this); } nouser++; this.mode = mode; } } public void Release() { lock(this) { nouser--; Monitor.PulseAll(this); } } } class MyThread { private MultiSemaphore sem; private bool excl; public MyThread(MultiSemaphore sem, bool excl) { this.sem = sem; this.excl = excl; } public void Run() { sem.Get(excl ? MultiSemaphore.EXCLUSIVE : MultiSemaphore.SHARED); Thread.Sleep(3000); sem.Release(); } } class MainClass { private static void Test(bool excl) { long start = DateTime.Now.Ticks; MultiSemaphore sem = new MultiSemaphore(); Thread[] t = new Thread[10]; for (int i = 0; i < t.Length; i++) { t[i] = new Thread(new ThreadStart((new MyThread(sem, excl)).Run)); } for (int i = 0; i < t.Length; i++) { t[i].Start(); } Thread.Sleep(1000); for (int i = 0; i < t.Length; i++) { t[i].Join(); } long end = DateTime.Now.Ticks; Console.WriteLine((excl ? "Exclusive" : "Shared") + " time = " + (end - start)); } public static void Main(string[] args) { Test(true); Test(false); } } }