简体   繁体   English

我可以在 with 语句中获取多处理的 Lock 吗?

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

Horrible things can happen if a process fails to unlock a multiprocessing lock.如果一个进程无法解锁multiprocessing进程锁,就会发生可怕的事情。 To minimize the chance of that happening, I want to acquire the lock in a with block.为了尽量减少发生这种情况的机会,我想在with块中获取锁。 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.因为 Lock 是一个上下文管理器。 So is RLock, and Lock and RLock from threading. RLock 以及来自线程的 Lock 和 RLock 也是如此。

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" 文档确实声明它是“threading.Lock 的克隆”,因此您可以参考“在 with 语句中使用锁、条件和信号量”

[edit 2020: The documentation now mentions this explicitly ] [编辑 2020: 文档现在明确提到了这一点]

Yes you can.是的你可以。

The documentation for Lock states: Lock的文档指出:

class multiprocessing.Lock

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

Reading threading 's documentation:阅读threading的文档:

All of the objects provided by this module that have acquire() and release() methods can be used as context managers for a with statement.该模块提供的所有具有acquire()release()方法的对象都可以用作with语句的上下文管理器。

Yes.是的。 the documentation now specifically states that:文件现在明确指出:

Lock supports the context manager protocol and thus may be used in with statements. Lock支持上下文管理器协议,因此可以在with语句中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM