public void Relocate(NonSafeDinnerPlace from, int amountOfFood) { Table -= amountOfFood; from.Table += amountOfFood; }
public void DepositWithdrawTestWithMutex() { var tasks = new List <Task>(); var table = new NonSafeDinnerPlace(); var coach = new NonSafeDinnerPlace(); var tableMutex = new Mutex(); var coachMutex = new Mutex(); for (int i = 0; i < 10; i++) { tasks.Add(Task.Factory.StartNew(() => { for (int j = 0; j < 1000; j++) { bool haveTableLock = tableMutex.WaitOne(); try { table.Place(1); } finally { if (haveTableLock) { tableMutex.ReleaseMutex(); } } } })); tasks.Add(Task.Factory.StartNew(() => { for (int j = 0; j < 2000; j++) { bool haveCoachLock = coachMutex.WaitOne(); try { coach.EatFrom(1); } finally { if (haveCoachLock) { coachMutex.ReleaseMutex(); } } } })); tasks.Add(Task.Factory.StartNew(() => { for (int j = 0; j < 1000; j++) { bool haveTransferLock = WaitHandle.WaitAll(new [] { tableMutex, coachMutex }); try { table.Relocate(coach, 1); } finally { if (haveTransferLock) { tableMutex.ReleaseMutex(); coachMutex.ReleaseMutex(); } } } })); } Task.WaitAll(tasks.ToArray()); Assert.True(table.Table == 0); Assert.True(coach.Table == 0); }