daily pastebin goal
19%
SHARE
TWEET

Untitled

a guest Dec 11th, 2018 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Used to avoid “Race condition” of threads by mutually excluding the access to a common resource
  2.     lock(var\0
  3.     {//statement/group of statement
  4.     }
  5. When executed:
  6. locks the var for access from other threads
  7. execute thread needs access to var it must gain load.
  8.  
  9. eg: Synchronisation of access to common resource:
  10. A class account has a balance variable bal. It has deposit() to increase bal and withdraw() to decrease. To avoid simultaneous execution the methods must be protected by the lock statement.
  11.  
  12. Structure of the program
  13. Two threads Saver and Spander are accessing object of account class
  14.  
  15. class Account  //common reosurce
  16. {
  17.     double bal;
  18.    
  19.     public Account(double ibal)
  20.     { bal =ibal;
  21.     }
  22.    
  23.     public void Deposit(doublr awt)
  24.     {
  25.         lock(this)
  26.         {bal = bal+awt;}
  27.     }
  28.    
  29.     public void Withdraw(double awt)
  30.     {
  31.         lock(this)
  32.         {bal = bal-awt;}
  33.     }
  34. }
  35.  
  36.  
  37. //Two threads
  38.  
  39. class Saver
  40. {
  41.     Account acc;
  42.     public Saver(Account iAcc)
  43.     {
  44.         acc=iAcc;
  45.     }
  46.  
  47.     public Save()
  48.     {
  49.         a loop calling acc.Deposit(20);
  50.     }
  51.    
  52. class Spender
  53. {
  54.     Account acc; //common reource
  55.     public Spender(Account iAcc)
  56.     {
  57.         acc=iAcc;
  58.     }
  59.  
  60.     public void Spend(100)
  61.     {
  62.     a loop calling acc.Withdraw(100);
  63. }
  64.  
  65. Main Program
  66.  
  67. public static void Main(String []args)
  68. {
  69.     Account acc = new Account();
  70.     //.objects of two threads
  71.    
  72.     Saver saveObj = new Saver(acc);
  73.     Spender spendObj = new Spender(acc);
  74.     Thread tSave = new Thread(new ThreadStart(saveObj.Save));
  75.     Thread tSpend = new Thread(new ThreadSpend(saveObj.Save));
  76.     tSave.start();
  77.     tSpend.Start();
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top