I am reading Python threading module, as a method of the class Condition, __is_owned(self)
tests if current thread owns the lock or not:
def _is_owned(self):
# Return True if lock is owned by current_thread.
# This method is called only if __lock doesn't have _is_owned().
if self.__lock.acquire(0):
self.__lock.release()
return False
else:
return True
This test will fail if thread a has the lock, and thread b tries to test is it owns the lock, see the code below:
import thread
import time
lock = thread.allocate_lock()
def is_owned(lock):
if lock.acquire(0):
lock.release()
return False
else:
return True
def thread1(lock):
lock.acquire()
print 'thread 1 acquired lock, going to block'
print 'thread 1, lock is owned by me', is_owned(lock)
lock.acquire()
def thread2(lock):
time.sleep(5)
print 'thread 2 try to acquire lock, without waiting'
print 'thread 2: lock is owned by me', is_owned(lock)
thread.start_new_thread(thread1, (lock,))
thread.start_new_thread(thread2, (lock,))
The outputs are :
In [6]: run is_owned.py
thread 1 acquired lock, going to block
thread 1, lock is owned by me True
In [7]: thread 2 try to acquire lock, without waiting
thread 2: lock is owned by me True
In[7] shows here because of the sleep(5), the second acquire attempt will block the thread indefinitely.
Why is this a test for ownership?