⬅︎ Back to Python file with closing automatically
You can also do the same with locks as Lock class also implements context management protocol (it acquires lock on __enter__ and releases it on __exit__)from threading import Locklock = Lock()def somefunc():....with lock:........do_something_within_lock()(sorry, I had to use dots instead of spaces to indent code because I don't know how to mark it as a code in comment here)You can always be sure, that the code inside __exit__ method will always be invoked (just like with try-except-finally).
Comment
You can also do the same with locks as Lock class also implements context management protocol (it acquires lock on __enter__ and releases it on __exit__)
from threading import Lock
lock = Lock()
def somefunc():
....with lock:
........do_something_within_lock()
(sorry, I had to use dots instead of spaces to indent code because I don't know how to mark it as a code in comment here)
You can always be sure, that the code inside __exit__ method will always be invoked (just like with try-except-finally).