简体   繁体   English

如果Python线程在获得锁后死亡,会发生什么情况?

[英]What happens if a Python thread dies after acquiring a lock?

In my program I have a thread that just sends and gets updates from a server. 在我的程序中,我有一个线程仅从服务器发送和获取更新。 I try to handle exceptions gracefully, but just in case the thread dies I'd simply like to restart it. 我尝试优雅地处理异常,但是以防万一线程死了,我只是想重新启动它。 The problem is the thread acquires locks (Threading.RLock objects) before using certain resources, and I don't know what happens if the thread were to die after acquiring a lock but before releasing it. 问题是线程在使用某些资源之前先获取了锁(Threading.RLock对象),而且我不知道如果线程在获得锁之后但在释放锁之前死亡,将会发生什么情况。 How could I deal with such a situation? 我该如何处理这种情况?

If you acquire your locks using with statements : 如果您使用with语句获取锁

with whatever_lock:
    do_stuff()

or in properly constructed try-finally statements (less recommended, but sometimes necessary): 或在正确构造的try-finally语句中(不建议使用,但有时是必需的):

whatever_lock.acquire()
try:
    do_stuff()
finally:
    whatever_lock.release()

then if an exception occurs, the locks will be released as the exception propagates out of the control flow constructs in which the locks are acquired. 然后,如果发生异常,则在异常传播到获取锁的控制流构造之外时,将释放锁。

That means if you're doing things right, dying threads will generally release all their locks as they die. 这意味着,如果您做对了,死掉的线程通常会在死掉时释放所有锁。 On the other hand, if you don't acquire your locks safely, or if thread death can mean deadlock instead of unhandled exceptions, then locks may stay acquired when a thread dies. 另一方面,如果您不能安全地获取锁,或者如果线程死亡可能意味着死锁而不是未处理的异常,那么当线程死亡时,锁可能仍然保持获取状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM