简体   繁体   中英

Can I acquire multiprocessing's Lock in a with statement?

Horrible things can happen if a process fails to unlock a multiprocessing lock. To minimize the chance of that happening, I want to acquire the lock in a with block. Is there any built in way I can do this or do I need to roll my own?

Yes, you can just do:

mylock = multiprocessing.Lock()

with mylock:
    ...

as Lock is a context manager. So is RLock, and Lock and RLock from threading.

The documentation does state that it is "a clone of threading.Lock", so you can refer to "Using locks, conditions, and semaphores in the with statement"

[edit 2020: The documentation now mentions this explicitly ]

Yes you can.

The documentation for Lock states:

class multiprocessing.Lock

 A non-recursive lock object: a clone of `threading.Lock`.

Reading threading 's documentation:

All of the objects provided by this module that have acquire() and release() methods can be used as context managers for a with statement.

Yes. the documentation now specifically states that:

Lock supports the context manager protocol and thus may be used in with statements.

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