Example #1
0
        static void Main(string[] args)
        {
            var sticks = new Chopstick[5];
            for (int i = 0; i < 5; i++)
            {
                sticks[i] = new Chopstick();
            }

            var philosophers = new Philosopher[5];
            for (int i = 0; i < 5; i++)
            {
                philosophers[i] = new Philosopher(sticks[i],sticks[(i + 1) % 5],(i + 1).ToString());
            }

            var threads = new Thread[5];
            for (int i = 0; i < 5; i++)
            {
                threads[i] = new Thread(philosophers[i].Run);
            }

            foreach (var thread in threads)
            {
                thread.Start();
            }

            threads[0].Join();
        }
Example #2
0
        private bool TryEating(Philosopher philosopher)
        {
            if (Monitor.TryEnter(table.forks))
            {
                if (philosopher.left.isFree && philosopher.right.isFree)
                {
                    lock (philosopher.left)
                    {
                        lock (philosopher.right)
                        {
                            philosopher.TakeForks();
                            Monitor.Exit(table.forks);
                            philosopher.Eat();
                            return(true);
                        }
                    }
                }
                else
                {
                    Monitor.Exit(table.forks);
                }
            }

            return(false);
        }
        static void Main(string[] args)
        {
            // Construct philosophers and chopsticks
            var philosophers = Philosopher.InitializeDiningPhilosophers();

            Console.WriteLine("Dinner is starting!\n");

            // Spawn threads for each philosopher's eating cycle
            var philosopherThreads = new List <Thread>();

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

            // Wait for all philosopher's to finish eating
            foreach (var thread in philosopherThreads)
            {
                thread.Join();
            }

            // Done
            Console.WriteLine("Dinner is over!\n");

            foreach (var philosopher in philosophers)
            {
                string times = philosopher.timesEaten.ToString();
                Console.WriteLine(philosopher.Name + " Ate " + times + " times.");
            }

            Console.ReadLine();
        }
Example #4
0
        static void Main(string[] args)
        {
            var sticks = new Chopstick[5];

            for (int i = 0; i < 5; i++)
            {
                sticks[i] = new Chopstick();
            }

            var philosophers = new Philosopher[5];

            for (int i = 0; i < 5; i++)
            {
                philosophers[i] = new Philosopher(sticks[i], sticks[(i + 1) % 5], (i + 1).ToString());
            }

            var threads = new Thread[5];

            for (int i = 0; i < 5; i++)
            {
                threads[i] = new Thread(philosophers[i].Run);
            }

            foreach (var thread in threads)
            {
                thread.Start();
            }

            threads[0].Join();
        }
        public DiningPhilosophersForm()
        {
            InitializeComponent();

            for (int i = 0; i < NR; i++)
            {
                sticks[i] = new Sticks(1, 1);
            }

            for (int i = 0; i < NR; i++)
            {
                phils[i] = new Philosopher(sticks[i], sticks[(i + NR - 1) % NR], this);
                Thread t = new Thread(phils[i].Run);
                t.IsBackground = true;
                t.Start();
            }

            colors[0] = Color.Green;
            colors[1] = Color.Red;
            colors[2] = Color.Blue;
            colors[3] = Color.Yellow;
            colors[4] = Color.Magenta;
            //colors[5] = Color.Cyan;
            //colors[6] = Color.Pink;
        }
 public void AddRequest(Philosopher philosopher)
 {
     _requestNames.Add(philosopher.Name);
     _requests.Enqueue(new Request {
         Philosopher = philosopher
     }, 0);
     EventManager.Broadcast("RequestAdded");
 }
 public Philosopher(int name, Fork leftFork, Fork rightFork, Philosopher allPhilosopher)
 {
     this.Name       = name;
     this._leftFork  = leftFork;
     this._rightFork = rightFork;
     //this._allPhilosophers = allPhilosopher;
     this._rnd = new Random(this.Name);
 }
        static void Main()
        {
            Philosopher[] philosophers      = new Philosopher[nDimension];
            Chopstick[]   chopsticks        = new Chopstick[nDimension];
            Thread[]      philosopherThread = new Thread[nDimension];

            String sTemp;
            Random rnd = new Random();
            int    randomNumber;

            for (int i = 0; i < nDimension; i++)
            {
                chopsticks[i] = new Chopstick(i);
            }
            for (int i = 0; i < nDimension; i++)
            {
                sTemp = "";
                Chopstick cLeft  = chopsticks[getLeft(i)];
                Chopstick cRight = chopsticks[getRight(i)];
                while (sTemp == "") //name all philosophers
                {
                    randomNumber = rnd.Next(111);
                    if (top111[randomNumber] != "")
                    {
                        sTemp = top111[randomNumber];
                        top111[randomNumber] = "";
                    }
                }
                philosophers[i]      = new Philosopher(i, sTemp, cLeft, cRight);
                cLeft.pNeighborR     = philosophers[i]; //right neighbor of the left chopstick is the philosopher himself
                cRight.pNeighborL    = philosophers[i]; //left neighbor of the right chopstick is the philosopher himself
                philosopherThread[i] = new Thread(philosophers[i].Engage);
            }
            foreach (Chopstick chopstick in chopsticks)
            {
                if (chopstick.pNeighborL.nMyID > chopstick.pNeighborR.nMyID)
                {
                    chopstick.pHasIt = chopstick.pNeighborR;                                                          //Philosopher with smaller ID gets it
                }
                else
                {
                    chopstick.pHasIt = chopstick.pNeighborL;
                }
            }
            foreach (Philosopher philosopher in philosophers)
            {
                philosopher.Initialize();
            }
            for (int i = 0; i < nDimension; i++)
            {
                philosopherThread[i].Start();                                  //start each thread
            }
            for (int i = 0; i < nDimension; i++)
            {
                philosopherThread[i].Join();
            }
            Console.ReadLine();
        }
            //define neighbors and give/take chopsticks actions on both sides
            public void Initialize()
            {
                Philosopher pContenderL = cMyLeft.Contender(this);  //Philosopher on the left
                Philosopher pContenderR = cMyRight.Contender(this); //Philosopher on the right

                pContenderL.Request += GiveChopstick;               //ask for and give both chopsticks
                pContenderR.Request += GiveChopstick;
                pContenderL.Release += TakeChopstick;
                pContenderR.Release += TakeChopstick;
            }
Example #10
0
        public MainWindow()
        {
            InitializeComponent();

            philosofer0 = new Philosopher("0", fork0, fork4);
            philosofer1 = new Philosopher("1", fork1,  fork0);
            philosofer2 = new Philosopher("2", fork2, fork1);
            philosofer3 = new Philosopher("3", fork3, fork2);
            philosofer4 = new Philosopher("4", fork4, fork3);

            #region Subscribe
            philosofer0.Think += OnThink;
            philosofer0.GetFork += OnTakedFork;
            philosofer0.EatEvent += OnEatEvent;
            philosofer0.PutFork += OnPutFork;

            philosofer1.Think += OnThink;
            philosofer1.GetFork += OnTakedFork;
            philosofer1.EatEvent += OnEatEvent;
            philosofer1.PutFork += OnPutFork;

            philosofer2.Think += OnThink;
            philosofer2.GetFork += OnTakedFork;
            philosofer2.EatEvent += OnEatEvent;
            philosofer2.PutFork += OnPutFork;

            philosofer3.Think += OnThink;
            philosofer3.GetFork += OnTakedFork;
            philosofer3.EatEvent += OnEatEvent;
            philosofer3.PutFork += OnPutFork;

            philosofer4.Think += OnThink;
            philosofer4.GetFork += OnTakedFork;
            philosofer4.EatEvent += OnEatEvent;
            philosofer4.PutFork += OnPutFork;
            #endregion

            helperOnThink = HelperOnThink;
            helperOnTaked = HelpOnGetFork;
            helperOnEat = HelpOnEatEvent;
            helperOnPut = HelpOnPutFork;

            thread0 = new Thread(philosofer0.Action);
            thread1 = new Thread(philosofer1.Action);
            thread2 = new Thread(philosofer2.Action);
            thread3 = new Thread(philosofer3.Action);
            thread4 = new Thread(philosofer4.Action);

            thread0.Start();
            thread1.Start();
            thread2.Start();
            thread3.Start();
            thread4.Start();
        }
Example #11
0
        public MainWindow()
        {
            InitializeComponent();

            philosofer0 = new Philosopher("0", fork0, fork4);
            philosofer1 = new Philosopher("1", fork1, fork0);
            philosofer2 = new Philosopher("2", fork2, fork1);
            philosofer3 = new Philosopher("3", fork3, fork2);
            philosofer4 = new Philosopher("4", fork4, fork3);

            #region Subscribe
            philosofer0.Think    += OnThink;
            philosofer0.GetFork  += OnTakedFork;
            philosofer0.EatEvent += OnEatEvent;
            philosofer0.PutFork  += OnPutFork;

            philosofer1.Think    += OnThink;
            philosofer1.GetFork  += OnTakedFork;
            philosofer1.EatEvent += OnEatEvent;
            philosofer1.PutFork  += OnPutFork;

            philosofer2.Think    += OnThink;
            philosofer2.GetFork  += OnTakedFork;
            philosofer2.EatEvent += OnEatEvent;
            philosofer2.PutFork  += OnPutFork;

            philosofer3.Think    += OnThink;
            philosofer3.GetFork  += OnTakedFork;
            philosofer3.EatEvent += OnEatEvent;
            philosofer3.PutFork  += OnPutFork;

            philosofer4.Think    += OnThink;
            philosofer4.GetFork  += OnTakedFork;
            philosofer4.EatEvent += OnEatEvent;
            philosofer4.PutFork  += OnPutFork;
            #endregion

            helperOnThink = HelperOnThink;
            helperOnTaked = HelpOnGetFork;
            helperOnEat   = HelpOnEatEvent;
            helperOnPut   = HelpOnPutFork;

            thread0 = new Thread(philosofer0.Action);
            thread1 = new Thread(philosofer1.Action);
            thread2 = new Thread(philosofer2.Action);
            thread3 = new Thread(philosofer3.Action);
            thread4 = new Thread(philosofer4.Action);

            thread0.Start();
            thread1.Start();
            thread2.Start();
            thread3.Start();
            thread4.Start();
        }
 //return the other contender on the chopstick
 public Philosopher Contender(Philosopher pContender)
 {
     if (pNeighborL == pContender)
     {
         return(pNeighborR);
     }
     else
     {
         return(pNeighborL);
     }
 }
Example #13
0
        public async Task <bool> Request(Philosopher philosopher)
        {
            var completionSource = new TaskCompletionSource <bool>();

            EventManager.Subscribe(philosopher.Name + "RequestGranted", (name) =>
            {
                completionSource.SetResult(true);
            });
            _requestQueue.AddRequest(philosopher);
            await completionSource.Task.ConfigureAwait(false);

            return(true);
        }
        static void Main(string[] args)
        {
            Philosopher p1 = new Philosopher("Philosopher 1", f5, f1);
            Philosopher p2 = new Philosopher("Philosopher 2", f1, f2);
            Philosopher p3 = new Philosopher("Philosopher 3", f2, f3);
            Philosopher p4 = new Philosopher("Philosopher 4", f3, f4);
            Philosopher p5 = new Philosopher("Philosopher 5", f4, f5);

            new Thread(p1.Eat).Start();
            new Thread(p2.Eat).Start();
            new Thread(p3.Eat).Start();
            new Thread(p4.Eat).Start();
            new Thread(p5.Eat).Start();
        }
Example #15
0
 public DiningProcess(int philNumb)
 {
     philosophersNum = philNumb;
     forks           = new List <Fork>();
     philosophers    = new List <Philosopher>();
     threads         = new List <Thread>();
     for (int i = 0; i < philosophersNum; i++)
     {
         Philosopher philosopher = new Philosopher(i);
         philosophers.Add(philosopher);
         Fork fork = new Fork(i);
         forks.Add(fork);
     }
     Waiter.Instance.InitWaiter(forks);
 }
Example #16
0
        public DiningTable(int nPhilosophers)
        {
            Fork[] forks = new Fork[nPhilosophers];

            for (int nFork = 0; nFork < nPhilosophers; nFork++)
            {
                forks[nFork] = new Fork(nFork);
            }

            philosophers = new Philosopher[nPhilosophers];

            for (int nPhilospher = 0; nPhilospher < philosophers.Length; nPhilospher++)
            {
                philosophers[nPhilospher] = new Philosopher(nPhilospher, forks[nPhilospher], forks[(nPhilospher + 1) % nPhilosophers]);
            }
        }
Example #17
0
        static void Main(string[] args)
        {
            while (true)
            {
                bool[] forksAvailable = new bool[5] {
                    true, true, true, true, true
                };

                for (int i = 0; i < 5; i++)
                {
                    Philosopher p = new Philosopher(i, ref forksAvailable);
                }

                Thread.Sleep(1000);
            }
        }
Example #18
0
        private void Think(object philosopher)
        {
            Philosopher phil = philosopher as Philosopher;

            if (phil == null)
            {
                return;
            }

            while (true)
            {
                if (TryEating(phil))
                {
                    Console.WriteLine($"Philosopher {phil.Number} is thinking");
                    Thread.Sleep(500);
                }
            }
        }
Example #19
0
        public Table(int number)
        {
            this.NumOfPhilosophers = number;
            this.philosophers      = new Philosopher[NumOfPhilosophers];
            this.forks             = new Fork[NumOfPhilosophers];

            for (int i = 0; i < forks.Length; i++)
            {
                forks[i] = new Fork(i);
            }

            for (int i = 0; i < NumOfPhilosophers; i++)
            {
                Fork right = forks[i];
                Fork left  = forks[(i + 1) % NumOfPhilosophers];
                philosophers[i] = new Philosopher(i, left, right);
            }
        }
Example #20
0
        public DiningTable(int nPhilosophers)
        {
            Fork[] forks = new Fork[nPhilosophers];

            for (int nFork = 0; nFork < nPhilosophers; nFork++)
            {
                forks[nFork] = new Fork(nFork);
            }

            philosophers = new Philosopher[nPhilosophers];

            SemaphoreSlim tableSemaphore = new SemaphoreSlim(nPhilosophers / 2);

            for (int nPhilospher = 0; nPhilospher < philosophers.Length; nPhilospher++)
            {
                philosophers[nPhilospher] = new Philosopher(nPhilospher, forks[nPhilospher], forks[(nPhilospher + 1) % nPhilosophers], tableSemaphore);
            }
        }
Example #21
0
File: Program.cs Project: KavTV/H2
        static void Main(string[] args)
        {
            List <Fork> forkList = new List <Fork>();

            forkList.Add(new Fork(1));
            forkList.Add(new Fork(2));
            forkList.Add(new Fork(3));
            forkList.Add(new Fork(4));
            forkList.Add(new Fork(5));

            Philosopher phil1 = new Philosopher(1, forkList[0], forkList[1]);
            Philosopher phil2 = new Philosopher(2, forkList[1], forkList[2]);
            Philosopher phil3 = new Philosopher(3, forkList[2], forkList[3]);
            Philosopher phil4 = new Philosopher(4, forkList[3], forkList[4]);
            Philosopher phil5 = new Philosopher(5, forkList[4], forkList[0]);

            Console.Read();
        }
Example #22
0
        public TableViewModel()
        {
            PhilosopherThinkingTime = "2000";

            fork1 = new Fork();
            fork2 = new Fork();
            fork3 = new Fork();
            fork4 = new Fork();
            fork5 = new Fork();

            philosopher1 = new Philosopher("1", fork1, fork2);
            philosopher2 = new Philosopher("2", fork2, fork3);
            philosopher3 = new Philosopher("3", fork3, fork4);
            philosopher4 = new Philosopher("4", fork4, fork5);
            philosopher5 = new Philosopher("5", fork5, fork1);

            this.RunCommand  = new RelayCommand(this.OnRun, this.CanRun);
            this.StopCommand = new RelayCommand(this.OnStop, this.CanStop);
        }
Example #23
0
        static void Main(string[] args)
        {
            QF.Instance.Initialize((int)DPPSignal.MaxSignal - 1);

            IQActive table = new Table(c_NumberOfPhilosophers);
            IQActive[] philosophers = new IQActive[c_NumberOfPhilosophers];

            for(int i = 0; i < c_NumberOfPhilosophers; i++)
            {
                philosophers[i] = new Philosopher(i);
            }

            Console.WriteLine(c_NumberOfPhilosophers + " philosophers gather around a table thinking ...");
            table.Start(c_NumberOfPhilosophers);
            for(int i = 0; i < c_NumberOfPhilosophers; i++)
            {
                philosophers[i].Start(i);
            }
        }
Example #24
0
        static void Main(string[] args)
        {
            QF.Instance.Initialize((int)DPPSignal.MaxSignal - 1);

            IQActive table = new Table(c_NumberOfPhilosophers);

            IQActive[] philosophers = new IQActive[c_NumberOfPhilosophers];

            for (int i = 0; i < c_NumberOfPhilosophers; i++)
            {
                philosophers[i] = new Philosopher(i);
            }

            Console.WriteLine(c_NumberOfPhilosophers + " philosophers gather around a table thinking ...");
            table.Start(c_NumberOfPhilosophers);
            for (int i = 0; i < c_NumberOfPhilosophers; i++)
            {
                philosophers[i].Start(i);
            }
        }
 //Philosopher takes the chopstick
 void TakeChopstick(Chopstick chopstick, Philosopher pWho)
 {
     if (pWho != this)
     {
         return;
     }
     if (chopstick == cMyLeft)
     {
         cTakeFromL = null;                       //have taken it
     }
     else
     {
         cTakeFromR = null;
     }
     lock (chopstick)
     {
         chopstick.pHasIt = this; //it's mine
     }
     Console.WriteLine("{0} takes chopstick number {1} from {2} and has {3} chopstick(s)", sName, chopstick.nChopstickID, chopstick.Contender(this).sName, HaveChopsticks());
 }
Example #26
0
 public static void Init()
 {
     Philosopher[] tmpP = new Philosopher[numberOfPhilosophers];
     Fork[]        tmpF = new Fork[numberOfPhilosophers];
     for (int i = 0; i < numberOfPhilosophers; i++)
     {
         tmpF[i] = Fork.Create();
     }
     for (int i = 0; i < numberOfPhilosophers; i++)
     {
         Philosopher p = Philosopher.Create();
         p.left  = tmpF[i];
         p.right = tmpF[(i + 1) % numberOfPhilosophers];
         tmpP[i] = p;
     }
     for (int i = 0; i < numberOfPhilosophers; i++)
     {
         phils = phils.Add(tmpP[i]);
     }
     mode = Mode.Running;
 }
        static void Main()
        {
            Philosopher[] philosophers = new Philosopher[nDimension];
            Chopstick[] chopsticks = new Chopstick[nDimension];
            Thread[] philosopherThread = new Thread[nDimension];

            String sTemp;
            Random rnd = new Random();
            int randomNumber;

            for (int i = 0; i < nDimension; i++) chopsticks[i] = new Chopstick(i);
            for (int i = 0; i < nDimension; i++)
            {
                sTemp = "";
                Chopstick cLeft = chopsticks[getLeft(i)];
                Chopstick cRight = chopsticks[getRight(i)];
                while (sTemp == "") //name all philosophers
                {
                    randomNumber = rnd.Next(111);
                    if (top111[randomNumber] != "")
                    {
                        sTemp = top111[randomNumber];
                        top111[randomNumber] = "";
                    }
                }
                philosophers[i] = new Philosopher(i, sTemp, cLeft, cRight);
                cLeft.pNeighborR = philosophers[i]; //right neighbor of the left chopstick is the philosopher himself
                cRight.pNeighborL = philosophers[i]; //left neighbor of the right chopstick is the philosopher himself
                philosopherThread[i] = new Thread(philosophers[i].Engage);
            }
            foreach (Chopstick chopstick in chopsticks)
            {
                if (chopstick.pNeighborL.nMyID > chopstick.pNeighborR.nMyID) chopstick.pHasIt = chopstick.pNeighborR; //Philosopher with smaller ID gets it
                else chopstick.pHasIt = chopstick.pNeighborL;
            }
            foreach (Philosopher philosopher in philosophers) philosopher.Initialize();
            for (int i = 0; i < nDimension; i++) philosopherThread[i].Start(); //start each thread
            for (int i = 0; i < nDimension; i++) philosopherThread[i].Join();
            Console.ReadLine();
        }
Example #28
0
        /// <summary>
        /// 	The entry point of the program, where the program control starts and ends.
        /// </summary>
        /// <param name="args">The command-line arguments.</param>
        static void Main(string[] args)
        {
            // Permission to eat.
            ConcurrencyUtils.FIFOSemaphore eatPermission = new ConcurrencyUtils.FIFOSemaphore();

            //Initialize the five forks.
            ConcurrencyUtils.Mutex fork1 = new ConcurrencyUtils.Mutex();
            ConcurrencyUtils.Mutex fork2 = new ConcurrencyUtils.Mutex();
            ConcurrencyUtils.Mutex fork3 = new ConcurrencyUtils.Mutex();
            ConcurrencyUtils.Mutex fork4 = new ConcurrencyUtils.Mutex();
            ConcurrencyUtils.Mutex fork5 = new ConcurrencyUtils.Mutex();

            // Initialise the Philosophers with their left and right fork and eat Permission.
            Philosopher p1 = new Philosopher(fork1, fork2, eatPermission);
            Philosopher p2 = new Philosopher(fork2, fork3, eatPermission);
            Philosopher p3 = new Philosopher(fork3, fork4, eatPermission);
            Philosopher p4 = new Philosopher(fork4, fork5, eatPermission);
            Philosopher p5 = new Philosopher(fork5, fork1, eatPermission);

            // Create and start all the Philosopher's threads.
            Thread t1 = new Thread(p1.BeginLifeAmbitions);
            t1.Name = "P1";
            Thread t2 = new Thread(p2.BeginLifeAmbitions);
            t2.Name = "\tP2";
            Thread t3 = new Thread(p3.BeginLifeAmbitions);
            t3.Name = "\t\tP3";
            Thread t4 = new Thread(p4.BeginLifeAmbitions);
            t4.Name = "\t\t\tP4";
            Thread t5 = new Thread(p5.BeginLifeAmbitions);
            t5.Name = "\t\t\t\tP5";

            t1.Start();
            t2.Start();
            t3.Start();
            t4.Start();
            t5.Start();

            // Release only 4 tokens into eat permission to ensure no deadlock.
            eatPermission.Release(4);
        }
Example #29
0
        public static void Main(string[] args)
        {
            MySemaphore lConductor = new MySemaphore(4);

            MyMutex fForkOne   = new MyMutex();
            MyMutex fForkTwo   = new MyMutex();
            MyMutex fForkThree = new MyMutex();
            MyMutex fForkFour  = new MyMutex();
            MyMutex fForkFive  = new MyMutex();

            Philosopher lPhilosopherOne   = new Philosopher("Philosopher One", fForkFive, fForkOne, lConductor);
            Philosopher lPhilosopherTwo   = new Philosopher("Philosopher Two", fForkOne, fForkTwo, lConductor);
            Philosopher lPhilosopherThree = new Philosopher("Philosopher Three", fForkTwo, fForkThree, lConductor);
            Philosopher lPhilosopherFour  = new Philosopher("Philosopher Four", fForkThree, fForkFour, lConductor);
            Philosopher lPhilosopherFive  = new Philosopher("Philosopher Five", fForkFour, fForkFive, lConductor);

            lPhilosopherOne.Start();
            lPhilosopherTwo.Start();
            lPhilosopherThree.Start();
            lPhilosopherFour.Start();
            lPhilosopherFive.Start();
        }
Example #30
0
 public void release(Philosopher p)
 {
     hasMe = default(Philosopher);
 }
 //return the other contender on the chopstick
 public Philosopher Contender(Philosopher pContender)
 {
     if (pNeighborL == pContender) return pNeighborR;
     else return pNeighborL;
 }
Example #32
0
        public void PutDown(Philosopher philospher)
        {
            Debug.Assert(owner == philospher);

            owner = null;
        }
Example #33
0
        public void PickUp(Philosopher philospher)
        {
            Debug.Assert(owner == null);

            owner = philospher;
        }
 //Philosopher takes the chopstick
 void TakeChopstick(Chopstick chopstick, Philosopher pWho)
 {
     if (pWho != this) return;
     if (chopstick == cMyLeft) cTakeFromL = null; //have taken it
     else cTakeFromR = null;
     lock (chopstick)
     {
         chopstick.pHasIt = this; //it's mine
     }
     Console.WriteLine("{0} takes chopstick number {1} from {2} and has {3} chopstick(s)", sName, chopstick.nChopstickID, chopstick.Contender(this).sName, HaveChopsticks());
 }
Example #35
0
 public static void TakeLeft([Domain("phils")] Philosopher p)
 {
     p.left.take(p);
     p.state = State.Waiting;
 }
Example #36
0
 public void Drop()
 {
     Monitor.Exit(syncRoot);
     this.Owner  = null;
     this.Status = "";
 }
Example #37
0
        static void Main(string[] args)
        {
            Stopwatch watch = new Stopwatch();
            int       n, thinkingTime, eatingTime;
            int       waitedForFork = 0;
            string    consoleInput;

            Console.Write("Enter number of philosophers: ");
            consoleInput = Console.ReadLine();
            n            = int.Parse(consoleInput);

            Console.Write("Enter max thinking time in ms: ");
            consoleInput = Console.ReadLine();
            thinkingTime = int.Parse(consoleInput);

            Console.Write("Enter max eating time in ms: ");
            consoleInput = Console.ReadLine();
            eatingTime   = int.Parse(consoleInput);

            Console.WriteLine();

            watch.Start();
            CancellationTokenSource source = new CancellationTokenSource();

            forks = new object[n];
            Task[] pTasks = new Task[n];

            #region Deadlock
            //for (int i = 0; i < n; i++)
            //{
            //    forks[i] = new object();
            //}

            //pTasks[0] = new Task(() =>
            //{
            //    Philosopher p = new Philosopher();
            //    p.Eat(forks[n - 1], forks[0],
            //        n - 1, 0, 0, thinkingTime, eatingTime, source.Token);
            //});
            //pTasks[0].Start();

            //for (int i = 1; i < n; i++)
            //{
            //    int ix = i;
            //    pTasks[i] = new Task(() =>
            //    {
            //        Philosopher p = new Philosopher();
            //        p.Eat(forks[ix - 1], forks[ix],
            //            ix - 1, ix, ix, thinkingTime, eatingTime, source.Token);
            //    });
            //    pTasks[i].Start();
            //}
            #endregion

            #region NoCircularWait
            for (int i = 0; i < n; i++)
            {
                forks[i] = new object();
            }

            pTasks[0] = new Task(() =>
            {
                Philosopher p = new Philosopher();
                p.Eat(forks[0], forks[n - 1],
                      n - 1, 0, 0, thinkingTime, eatingTime, source.Token);

                Interlocked.Add(ref waitedForFork, (int)p.WaitForFork);
            });
            pTasks[0].Start();

            for (int i = 1; i < n; i++)
            {
                int ix = i;
                pTasks[i] = new Task(() =>
                {
                    Philosopher p = new Philosopher();

                    if (n % 2 == 1)
                    {
                        p.Eat(forks[ix - 1], forks[ix],
                              ix - 1, ix, ix, thinkingTime, eatingTime, source.Token);
                    }
                    else
                    {
                        p.Eat(forks[ix], forks[ix - 1],
                              ix - 1, ix, ix, thinkingTime, eatingTime, source.Token);
                    }

                    Interlocked.Add(ref waitedForFork, (int)p.WaitForFork);
                });
                pTasks[i].Start();
            }
            #endregion

            // Let them eat
            Thread.Sleep(1000);

            // Stop eating
            source.Cancel();

            // Wait till all finished
            Task.WaitAll(pTasks);

            watch.Stop();

            Console.WriteLine($"\n{watch.ElapsedMilliseconds}ms waittime\n{waitedForFork}ms sum waited for fork\nPress any key to exit.");
            Console.ReadLine();
        }