Sma*_*ron 4 python multithreading python-multithreading
锁机制(以及其他机制)的存在是为了防止不同线程同时访问共享资源。想要使用资源的线程被阻塞,必须等待锁释放才能继续。(如果我错了纠正我)
如何判断线程何时等待释放锁,何时不释放?换句话说,如何知道线程何时被阻塞?。
如果这是可能的,我怎么知道这种情况发生了多少次?
您可以使用该函数的可选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
Run Code Online (Sandbox Code Playgroud)
打印语句只是为了显示正在发生的事情,用您想要使用的任何逻辑替换它,例如维护线程阻塞的次数计数器。
| 归档时间: |
|
| 查看次数: |
2032 次 |
| 最近记录: |