public void TransferUsingLockOrdering(BankAccount otherAcct, decimal money) { Object firstlock; Object secondlock; ChooseLocks(this, otherAcct, out firstlock, out secondlock); Console.WriteLine("{3} Transfer {2:C0} from AccID: {0} to AccID: {1}", otherAcct.acctID, this.acctID, money, Thread.CurrentThread.Name); lock (firstlock) { Thread.Sleep(100); lock (secondlock) { otherAcct.Debit(money); this.Credit(money); } } }
public void Transfer(BankAccount otherAcct, decimal money) { Mutex[] mut = { this._lockMutex, otherAcct._lockMutex}; Console.WriteLine("{3} Transfer {2:C0} from AccID: {0} to AccID: {1}", otherAcct.acctID, this.acctID, money, Thread.CurrentThread.Name); if (WaitHandle.WaitAll(mut)) { try { Thread.Sleep(100); { otherAcct.Debit(money); this.Credit(money); } } finally { foreach (Mutex m in mut) { m.ReleaseMutex(); } } } }
public void Transfer(BankAccount otherAcct, decimal money) { Mutex[] mut = { this._lockMutex, otherAcct._lockMutex }; Console.WriteLine("{3} Transfer {2:C0} from AccID: {0} to AccID: {1}", otherAcct.acctID, this.acctID, money, Thread.CurrentThread.Name); if (WaitHandle.WaitAll(mut)) { try { Thread.Sleep(100); { otherAcct.Debit(money); this.Credit(money); } } finally { foreach (Mutex m in mut) { m.ReleaseMutex(); } } } }