简体   繁体   中英

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. How could I deal with such a situation?

If you acquire your locks using with statements :

with whatever_lock:
    do_stuff()

or in properly constructed try-finally statements (less recommended, but sometimes necessary):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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