Exemplo n.º 1
0
 public static void Transfer(Account source, Account destination, double funds)
 {
     lock (source)
     {
         lock (destination)
         {
             source.m_Balance -= funds;
             destination.m_Balance += funds;
         }
     }
 }
Exemplo n.º 2
0
        private static void Demo2()
        {
            Random rnd = new Random();
            Account a1 = new Account(1234.12);
            Account a2 = new Account(56789.56);

            Thread t1 = new Thread(delegate()
            {
                while (true)
                {
                    double funds = rnd.NextDouble() * 100;
                    Account.Transfer(a1, a2, funds);
                    Console.WriteLine(string.Format("Transferred {0} from A1({1}) to A2({2})", funds,  a1.Balance, a2.Balance));
                    Thread.Sleep((int)(rnd.NextDouble() * 10));
                }
            });

            Thread t2 = new Thread(delegate()
            {
                while (true)
                {
                    double funds = rnd.NextDouble() * 100;
                    Account.Transfer(a2, a1, funds);
                    Console.WriteLine(string.Format("Transferred {0} from A2({1}) to A1({2})", funds, a1.Balance, a2.Balance));
                    Thread.Sleep((int)(rnd.NextDouble() * 10));
                }
            });

            t1.Start();
            t2.Start();

            t1.Join();
            t2.Join();
        }