//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; }
//Responds to a request for the chopstick void GiveChopstick(Chopstick chopstick) { if (chopstick.pHasIt != this) { return; //doesn't have it } if (chopstick.bDirty) //used - philosopher has eaten (or initial state) - will give it { Console.WriteLine("{0} accepted request for chopstick number {1} from {2}", sName, chopstick.nChopstickID, chopstick.Contender(this).sName); lock (chopstick) { chopstick.bDirty = false; chopstick.pHasIt = null; } Release(chopstick, chopstick.Contender(this)); } else //clean - decline, but will note the request { Console.WriteLine("{0} declined request for chopstick number {1} from {2}", sName, chopstick.nChopstickID, chopstick.Contender(this).sName); if (chopstick == cMyLeft) { cGiveToL = chopstick; //note that it was asked for } else { cGiveToR = chopstick; } } }
//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()); }
//Responds to a request for the chopstick void GiveChopstick(Chopstick chopstick) { if (chopstick.pHasIt != this) return; //doesn't have it if (chopstick.bDirty) //used - philosopher has eaten (or initial state) - will give it { Console.WriteLine("{0} accepted request for chopstick number {1} from {2}", sName, chopstick.nChopstickID, chopstick.Contender(this).sName); lock (chopstick) { chopstick.bDirty = false; chopstick.pHasIt = null; } Release(chopstick, chopstick.Contender(this)); } else //clean - decline, but will note the request { Console.WriteLine("{0} declined request for chopstick number {1} from {2}", sName, chopstick.nChopstickID, chopstick.Contender(this).sName); if (chopstick == cMyLeft) cGiveToL = chopstick; //note that it was asked for else cGiveToR = chopstick; } }
//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()); }