Custom Search

Tuesday, November 23, 2010

Python Class level Lock

==================================

* Class level lock.
* Here variable 'lock' is a class variable.
* So all objects using common lock.
* Here at a time only one object can acquire lock.
* Suppose object 'a' call the method 'my_function' and acquire the lock,
this time object 'b' or other objects can method 'my_function' but can not
acquire the lock until object 'a' release the lock, so object 'b' waiting in method
'my_function' for
acquire the lock.


import threading
class A:
lock = threading.RLock()

def my_function(self, name):
print "------Waiting for acquire lock------", name
self.lock.acquire()
try:
print "------lock acquired------", name
print "------sleeping----start----", name
import time
time.sleep(5)
print "------sleeping----end------", name
finally:
self.lock.release()
print "------lock released-------", name

a = A()
b = A()

thr1 = threading.Thread(name='a.my_function',target=a.my_function, args=('T1',))
thr2 = threading.Thread(name='b.my_function', target=b.my_function, args=('T2',))

print "----------calling------thr1.start()------"
thr1.start()
print "----------calling------thr2.start()------"
thr2.start()

----------------------------------------------------CASE-1

2 threads 'thr1' and 'thr2' trying to call a method 'my_function' of class 'A'
using two seperate objects 'a' and 'b'.

a = A()
b = A()

thr1 = threading.Thread(name='a.my_function',target=a.my_function, args=('T1',))
thr2 = threading.Thread(name='b.my_function', target=b.my_function, args=('T2',))


OUTPUT
======
----------calling------thr1.start()------
----------calling------thr2.start()------
------Waiting for acquire lock------ T1
------lock acquired------ T1
------sleeping----start---- T1
------Waiting for acquire lock------ T2
------sleeping----end------ T1
------lock released------- T1
------lock acquired------ T2
------sleeping----start---- T2
------sleeping----end------ T2
------lock released------- T2

----------------------------------------------------CASE-2

a = A()

thr1 = threading.Thread(name='a.my_function',target=a.my_function, args=('T1',))
thr2 = threading.Thread(name='a.my_function', target=a.my_function, args=('T2',))

OUTPUT
======
----------calling------thr1.start()------
----------calling------thr2.start()------
------Waiting for acquire lock------ T1
------lock acquired------ T1
------sleeping----start---- T1
------Waiting for acquire lock------ T2
------sleeping----end------ T1
------lock released------- T1
------lock acquired------ T2
------sleeping----start---- T2
------sleeping----end------ T2
------lock released------- T2


==================================

No comments:

Post a Comment