我正在阅读Python线程模块,作为类Condition的方法,__is_owned(self)
测试当前线程是否拥有锁:
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
如果线程a具有锁定,并且线程b尝试测试它是否拥有锁定,则此测试将失败,请参阅下面的代码:
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,))
输出结果为:
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
在[7]中显示由于sleep(5),第二次获取尝试将无限期地阻塞该线程。
为什么这是对所有权的测试?