What is the optimal use of locking when trying ... other than Python 2.7?

Suppose I have a threading.Lock() object that I want to acquire in order to use a resource. Suppose I want to use a try ... except ... clause with a resource.

There are several ways to do this.

Method 1

 import threading lock = threading.Lock() try: with lock: do_stuff1() do_stuff2() except: do_other_stuff() 

If an error occurs during do_stuff1() or do_stuff2() , will the lock be released? Or is it better to use one of the following methods?

Method 2

 with lock: try: do_stuff1() do_stuff2() except: do_other_stuff() 

Method 3

 lock.acquire(): try: do_stuff1() do_stuff2() except: do_other_stuff() finally: lock.release() 

Which method is best for locking even if an error occurs?

+6
source share
1 answer

with "context manager" requires the __exit__ method, which in this case ensures that no matter what happens, t22> - release d.

If you want to handle exceptions that occur during what you do with this lock , you must put try inside the with block, i.e. method 2 is the right approach. In general, you should always strive to minimize the amount of code in the try block.

You should also be as specific as possible about what might go wrong; naked except: - bad practice (see, for example, "evil except " ). At least (even for a simple example!) You should use except Exception:

+5
source

Source: https://habr.com/ru/post/984509/


All Articles