예제 #1
0
        static void Main(string[] args)
        {
            Servant serv         = new Servant();
            var     philosophers = InitializePhilosophers(serv);


            Console.WriteLine("Dinner is starting!"); // Start


            var philosopherThreads = new List <Thread>();

            foreach (var philosopher in philosophers)
            {
                var philosopherThread = new Thread(new ThreadStart(philosopher.EatAll));
                philosopherThreads.Add(philosopherThread);
                philosopherThread.Start();
            }



            foreach (var thread in philosopherThreads) // finish eating
            {
                thread.Join();
            }


            Console.WriteLine("Dinner is over!");
            Console.ReadKey();
        }
예제 #2
0
 public Philosopher(List <Philosopher> allPhilosophers, int index, Servant serv)
 {
     _serv            = serv;
     _allPhilosophers = allPhilosophers;
     _index           = index;
     this.Name        = string.Format("Philosopher {0}", _index);
     this.State       = State.Thinking;
 }
예제 #3
0
        private static List <Philosopher> InitializePhilosophers(Servant serv)
        {
            var philosophers = new List <Philosopher>(PHILOSOPHER_COUNT);

            for (int i = 0; i < PHILOSOPHER_COUNT; i++)
            {
                philosophers.Add(new Philosopher(philosophers, i, serv));
            }


            foreach (var philosopher in philosophers) // Assign chopsticks to philosophers
            {
                philosopher.LeftChopstick = philosopher.LeftPhilosopher.RightChopstick ?? new Chopstick();

                philosopher.RightChopstick = philosopher.RightPhilosopher.LeftChopstick ?? new Chopstick();
            }

            return(philosophers);
        }