Beispiel #1
0
        public static void driver()
        {
            for (int i = 1; i <= accounts.Length; i++)
            {
                accounts[i-1] = new BankAccount(i, SimulationProperties.INITIAL_AMT);
            }

            Thread[] threads = new Thread[SimulationProperties.NumberOfThreads];
            ThreadStart threadProc = new ThreadStart(Simulate);
            for (int i = 1; i <= threads.Length; i++)
            {
                threads[i - 1] = new Thread(threadProc);
                threads[i - 1].Name = String.Format("TX-{0}", i);
                threads[i - 1].Start();
            }

            Thread.Sleep(SimulationProperties.SimulationLength);
            IsSimulationOver = true;

            for (int i = 0; i < threads.Length; i++)
            {
                threads[i].Join();
            }
            VerifyAccoutns();
        }
Beispiel #2
0
        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();
                    }
                }
            }
        }
Beispiel #3
0
        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);
                }
            }
        }
Beispiel #4
0
 private void ChooseLocks(BankAccount acctOne, BankAccount acctTwo, out object firstlock, out object secondlock)
 {
     if (acctOne.acctID < acctTwo.acctID)
     {
         firstlock = acctOne._lock;
         secondlock = acctTwo._lock;
     }
     else
     {
         firstlock = acctTwo._lock;
         secondlock = acctOne._lock;
     }
 }