Reputation: 3458
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?
Upvotes: 4
Views: 4143
Reputation: 281748
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.
Upvotes: 5