Esempio n. 1
0
 public AccountManager(Account fromAccount, Account toAccount, double amountToTransfer)
 {
     this._fromAccount = fromAccount;
     this._toAccount = toAccount;
     this._amountToTransfer = amountToTransfer;
 }
Esempio n. 2
0
        /*
         * When a deadlock can occur,
         *      let's say we have 2 threads.
         *          a. Thread 1
         *          b. Thread 2
         *
         *      And 2 resources,
         *          a. Resource 1
         *          b. Resource 2
         *
         * Thread 1 has already acquired a lock on Resource 1 and wants to acquire a lock on Resource .
         * At the same time Thread 2 has already  acquired a lock on Resource 2 and wants to acquire a lock on Resource 1.
         *      Two threads never give up their locks, hence a deadlock.
         *
         * There are several ways to avoid and resolve deadlock.
         *      1. Acquiring locks in a specific defined order.
         *      2. Mutexclass.
         *      3. Monitor.TryEnter() method.
         *
         * In our current project we will use "Acquiring locks in a specific defined order."
         */
        static void Main(string[] args)
        {
            Console.WriteLine("Main Started");
            Account accountA = new Account(101, 4000);
            Account accountB = new Account(102, 3000);

            AccountManager accountManagerA = new AccountManager(accountA, accountB, 1000);
            Thread T1 = new Thread(accountManagerA.Transfer);
            T1.Name = "T1";

            AccountManager accountManagerB = new AccountManager(accountB, accountA, 2000);
            Thread T2 = new Thread(accountManagerB.Transfer);
            T2.Name = "T2";

            T1.Start();
            T2.Start();

            T1.Join();
            T2.Join();

            Console.WriteLine("Main completed.");
        }