Advertisement
ivandrofly

Threading - Deadlock

Mar 24th, 2014
376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.12 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace Deadlock
  5. {
  6.     internal class Program
  7.     {
  8.         private static void Main(string[] args)
  9.         {
  10.             Console.WriteLine("Main Started");
  11.             Account accountA = new Account(101, 5000);
  12.             Account accountB = new Account(101, 3000);
  13.  
  14.             var accountManagerA = new AccountManager(accountA, accountB, 1000);
  15.             var t1 = new Thread(accountManagerA.Transfer);
  16.             t1.Name = "#1 Thread";
  17.  
  18.             var accountManagerB = new AccountManager(accountB, accountA, 2000);
  19.             var t2 = new Thread(accountManagerB.Transfer);
  20.             t2.Name = "#2 Thread";
  21.  
  22.             t1.Start();
  23.             t2.Start();
  24.  
  25.             t1.Join();
  26.             t2.Join();
  27.             Console.WriteLine("Main Completed");
  28.         }
  29.     }
  30.  
  31.     internal class Account
  32.     {
  33.         private double _balance; private int _id;
  34.  
  35.         public int ID { get { return _id; } }
  36.  
  37.         public Account(int id, int balance)
  38.         {
  39.             // TODO: Complete member initialization
  40.             this._id = id;
  41.             this._balance = balance;
  42.         }
  43.  
  44.         public void WitdhDraw(double amount)
  45.         {
  46.             _balance -= amount;
  47.         }
  48.  
  49.         public void Deposit(double amount)
  50.         {
  51.             _balance += amount;
  52.         }
  53.     }
  54.  
  55.     internal class AccountManager
  56.     {
  57.         private Account _fromAccount;
  58.         private Account _toAccount;
  59.         private int _amountToTransfer;
  60.  
  61.         public AccountManager(Account fromAccount, Account toAccount, int amountToTransfer)
  62.         {
  63.             this._fromAccount = fromAccount;
  64.             this._toAccount = toAccount;
  65.             this._amountToTransfer = amountToTransfer;
  66.         }
  67.  
  68.         public void Transfer()
  69.         {
  70.             lock (_fromAccount)
  71.             {
  72.                 Thread.Sleep(1000);
  73.                 lock (_toAccount)
  74.                 {
  75.                     _fromAccount.WitdhDraw(_amountToTransfer);
  76.                     _toAccount.Deposit(_amountToTransfer);
  77.                 }
  78.             }
  79.         }
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement