.locked() returns True even after release() called in python multithreading environment -


i trying write first code using python thread.

please see code there issue when release lock thread using release() says lock still availabe [locked() returns true after release()]

import threading import time  class thread (threading.thread):     def __init__(self,t,d,arr,lock):         threading.thread.__init__(self)         self.name=t         self.delay=d         self.array=arr;         self.lock=lock     def run(self):        self.fun1()      def fun1(self):        print "the thread %s want take lock now" %self.name        self.lock.acquire()        print "lock status after lock acquire    foe",self.name,self.lock.locked()         time.sleep(self.delay)         print "release lock %s" %self.name        self.lock.release()        time.sleep(2)        print "lock status after lock release is",self.name,self.lock.locked()  lck=threading.lock()  obj1=thread('t1',5,[1,2,3],lck)  obj2=thread('t2',10,[4,5,6],lck)    obj1.start()  obj2.start() 

output

=====     thread t1 want take lock thread t2 want take lock  lock status after lock acquire foe t2 true release lock t2 lock status after lock acquire foe t1 true lock status after lock release t2 true release lock t1 lock status after lock release t1 false 

what problem is:

thread t2 got lock first , executed space. can see lock status t2 using .locked() "lock status after

lock acquire foe t2 true". t2 got lock now. once t2 released lock using release(), t1 acquired lock expected

but after lock release t2 using release(), locked() says true. means still lock available t2? in case how t1 acquired lock?. once t1 executed , after release(), can see .locked() returns false. means t1 locked() worked expected once releases lock, immediatly return false

so in nutshell, why first thread t2 returned true after lock release? if execute 1 thread works expected.

when pass lock object constructor, isn't getting copied, each thread object has access the same lock.

this results in self.lock.locked() returning true because lock is still locked, time has been locked by thread.

this happens:

>>> import threading >>> lck = threading.lock() # 'original' >>> lck2 = lck # lck2 isn't copy of lck! >>> lck.acquire() true >>> lck2.locked() # lck2 has been acquired lck  true >>> lck2.release() >>> lck.locked() # lck has been released lck2 false 

again, happens because lock objects aren't (and cannot be) copied around , whatever variable assigned lock, point original object.


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -