With a normal multiprocessing.Lock
(or threading.Lock
) you can simplify the following code:
lock = multiprocessing.Lock()
lock.acquire()
try:
...
finally:
lock.release()
into:
with lock:
...
However, can I still use a context manager when I want to pass some arguments to lock.acquire(...)
, such as block=
or timeout=
? For example, I have code like this:
lock_success = lock.acquire(block=False)
if not lock_success:
return
try:
...
finally:
lock.release()
I don't see a way to pass this argument to the context manager (since it's in the acquire
call and not the constructor).
(The idea is that the with
-block would get skipped if the lock cannot be acquired.)
Analogously for threading.Lock
which provides a similar API.