Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Used to avoid “Race condition” of threads by mutually excluding the access to a common resource
- lock(var\0
- {//statement/group of statement
- }
- When executed:
- locks the var for access from other threads
- execute thread needs access to var it must gain load.
- eg: Synchronisation of access to common resource:
- 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.
- Structure of the program
- Two threads Saver and Spander are accessing object of account class
- class Account //common reosurce
- {
- double bal;
- public Account(double ibal)
- { bal =ibal;
- }
- public void Deposit(doublr awt)
- {
- lock(this)
- {bal = bal+awt;}
- }
- public void Withdraw(double awt)
- {
- lock(this)
- {bal = bal-awt;}
- }
- }
- //Two threads
- class Saver
- {
- Account acc;
- public Saver(Account iAcc)
- {
- acc=iAcc;
- }
- public Save()
- {
- a loop calling acc.Deposit(20);
- }
- class Spender
- {
- Account acc; //common reource
- public Spender(Account iAcc)
- {
- acc=iAcc;
- }
- public void Spend(100)
- {
- a loop calling acc.Withdraw(100);
- }
- Main Program
- public static void Main(String []args)
- {
- Account acc = new Account();
- //.objects of two threads
- Saver saveObj = new Saver(acc);
- Spender spendObj = new Spender(acc);
- Thread tSave = new Thread(new ThreadStart(saveObj.Save));
- Thread tSpend = new Thread(new ThreadSpend(saveObj.Save));
- tSave.start();
- tSpend.Start();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement