// 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.Collections; using System.Threading; namespace E { public abstract class Command { public abstract void Execute(); } public class Test1Command : Command { private int v; public Test1Command(int v) { this.v = v; } public override void Execute() { Console.WriteLine("Test1 thread = " + Thread.CurrentThread.Name + " v = " + v); } } public class Test2Command : Command { private int v; public Test2Command(int v) { this.v = v; } public override void Execute() { Console.WriteLine("Test2 thread = " + Thread.CurrentThread.Name + " v = " + v); } } public class CommandQueue { private Queue q; public CommandQueue() { q = new Queue(); } public void Enqueue(Command cmd) { Monitor.Enter(q); q.Enqueue(cmd); Monitor.PulseAll(q); Monitor.Exit(q); } public Command Dequeue() { Command cmd = null; do { Monitor.Enter(q); if(q.Count > 0) { cmd = (Command)q.Dequeue(); } else { Monitor.Wait(q); } Monitor.Exit(q); } while(cmd == null); return cmd; } } public class WorkerThread { private CommandQueue cq; public WorkerThread(CommandQueue cq) { this.cq = cq; } public void Run() { while(true) { Command cmd = cq.Dequeue(); cmd.Execute(); } } } public class WorkerThreadPool { private WorkerThread[] wt; public WorkerThreadPool(int n, CommandQueue cq) { wt = new WorkerThread[n]; for(int i = 0; i < wt.Length; i++) { wt[i] = new WorkerThread(cq); Thread t = new Thread(new ThreadStart(wt[i].Run)); t.Name = "Thread-" + (i + 1); t.Start(); } } } public class TestClass { public static void Main(string[] args) { CommandQueue qc = new CommandQueue(); WorkerThreadPool wtp = new WorkerThreadPool(3, qc); qc.Enqueue(new Test1Command(1)); qc.Enqueue(new Test2Command(2)); qc.Enqueue(new Test1Command(3)); qc.Enqueue(new Test2Command(4)); Thread.Sleep(5000); Environment.Exit(0); } } }