using System; using System.Threading; public class Test { static void Main() { new Train(true); new Train(true); Thread.Sleep(100); new Train(false); new Train(true); new Train(false); Console.Read(); } } class Railway { public static Semaphore lock1 = new Semaphore(1, 1); } class Train { static Semaphore w_turnstile = new Semaphore(1, 1); static Semaphore w_mutex = new Semaphore(1, 1); static int w_counter = 0; static Semaphore e_turnstile = new Semaphore(1, 1); static Semaphore e_mutex = new Semaphore(1, 1); static int e_counter = 0; bool West; public Thread Thrd; public Train(bool west) { West = west; Thrd = new Thread(this.Run); Thrd.Name = west ? "запад" : "восток"; Thrd.Start(); } private Semaphore turnstile { get { return West ? w_turnstile : e_turnstile; } } private Semaphore turnstile2 { get { return West ? e_turnstile : w_turnstile; } } private Semaphore mutex { get { return West ? w_mutex : e_mutex; } } private int counter { get { return West ? w_counter : e_counter; } } private void Inc() { if(West) w_counter++; else e_counter++; } private void Dec() { if(West) w_counter--; else e_counter--; } void Run() { Console.WriteLine("- Подошёл поезд на {0}", Thrd.Name); turnstile.WaitOne(); turnstile.Release(); mutex.WaitOne(); Inc(); if(counter == 1) { turnstile2.WaitOne(); Railway.lock1.WaitOne(); Console.WriteLine("! Стрелка на {0}", Thrd.Name); turnstile2.Release(); } mutex.Release(); //движение поезда Console.WriteLine("( Едет поезд на {0} ({1})", Thrd.Name, counter); Thread.Sleep(1000); mutex.WaitOne(); Dec(); if(counter == 0) { Railway.lock1.Release(); } mutex.Release(); Console.WriteLine(") Проехал поезд на {0} ({1})", Thrd.Name, counter); } }