Esempio n. 1
0
 public void TransferFrom(BankAccount acct, decimal amt)
 {
     Console.WriteLine("[{0}] Transferring {1:C0} from account {2} to {3}", Thread.CurrentThread.Name, amt, acct.AccountNumber, this.AccountNumber);
     Mutex[] mutex = { this._lock, acct._lock };
     if (WaitHandle.WaitAll(mutex))
     {
         try
         {
             acct.Debit(amt);
             this.Credit(amt);
         }
         finally
         {
             foreach (Mutex m in mutex)
                 m.ReleaseMutex();
         }
     }
 }
Esempio n. 2
0
        static void Main(string[] args)
        {
            int procCnt = Environment.ProcessorCount;
            int num_threads = 10;
            int num_accts = 10;
            decimal initial_amt = 1000.00M;
            ba = new BankAccount[num_accts];
            Thread[] t = new Thread[num_threads];

            for (int i = 0; i < ba.Length; i++)
            {
                ba[i] = new BankAccount(i, initial_amt);
                t[i] = new Thread(new ThreadStart(RandomTransfer));
                t[i].Name = String.Format("TX: {0}", i);
            }

            for(int i = 0; i<num_threads; i++)
                t[i].Start();

            Thread.Sleep(5000);
            done = true;
            for (int i = 0; i < num_threads; i++)
                t[i].Join();

            //RandomTransfer();
            validateTransfer(num_accts, initial_amt);
            Console.ReadLine();
        }