锁机制(以及其他机制)的存在是为了防止不同线程同时访问共享资源。想要使用资源的线程被阻塞,必须等待锁释放才能继续执行。(如果我说错了,请纠正我)
如何确定一个线程是否在等待锁释放?换句话说,如何知道一个线程是否被阻塞?
如果这是可能的,那么如何确定发生了多少次这种情况?
如何确定一个线程是否在等待锁释放?换句话说,如何知道一个线程是否被阻塞?
如果这是可能的,那么如何确定发生了多少次这种情况?
blocking
参数来调用Lock.acquire()
函数。如果您将False
作为参数传递给Lock.acquire(False)
,则该函数会在无法获取锁(即已被其他线程持有)时返回False
,或者获取锁并返回True
。您可以根据以下逻辑使用此方法来确定您的线程是否会被阻塞:import threading
some_lock = threading.Lock()
# use this code anywhere you need to acquire the lock and check for blocking
if not some_lock.acquire(False):
print 'BLOCKING!'
some_lock.acquire() # call again with blocking=True (which is the default)
else:
print 'Acquired lock without blocking'
# lock has been acquired, make sure you release when done with critical section
这些print语句只是为了展示正在发生的事情,您可以用任何逻辑替换它们,例如维护一个线程被阻塞的次数计数器。
print
之外,else:
也可以被省略。 - martineauelse
只是为了说明不同的行为并清楚地表明即使您不进入 if 语句组,该锁仍然被获取。 - Andrew Clark