Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 806
alexgolec Avatar asked Aug 22 '13 16:08

alexgolec


2 Answers

Yes, you can just do:

with multiprocessing.Lock():
    ...

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]

like image 170
remram Avatar answered Oct 04 '22 02:10

remram


Yes. the documentation now specifically states that:

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

like image 41
Victor Bouhnik Avatar answered Oct 04 '22 03:10

Victor Bouhnik