[英]Acquiring a lock just before an async method starts
Let's say I have a multiprocessing.Lock
instance ( lock
below) that I want to acquire just before a coroutine foo
actually begins to run (say it is triggered by some future I/O or signal and so I don't want to hold the lock for the entire period that it is blocked, but rather just while it runs.) Is there any way to do this without modifying the body of foo
itself?假设我有一个
multiprocessing.Lock
实例(下面的lock
),我想在协程foo
实际开始运行之前获取它(假设它是由某些未来的 I/O 或信号触发的,所以我不想持有在它被阻塞的整个期间锁定,而不是在它运行时锁定。)有没有办法在不修改foo
本身的主体的情况下做到这一点? To illustrate:为了显示:
Without lock:无锁:
await foo()
With lock:带锁:
lock.acquire()
await foo()
lock.release()
As far as I can tell it doesn't help to wrap foo
inside another async
function because it still needs to be await
ed in the same manner.据我所知,将
foo
包装在另一个async
function 中没有帮助,因为它仍然需要以相同的方式await
。 It also doesn't help to deal with the asyncio.Future
directly, because all I can do is add_done_callback
.直接处理
asyncio.Future
也无济于事,因为我所能做的就是add_done_callback
。 Or any other concept of "chaining" callbacks is the same as wrapping it in an async
function-- if I put the lock acquisition future before the foo
future, it will just run right away effectively, and the lock will be held for the whole duration until foo
actually begins.或者“链接”回调的任何其他概念与将其包装在
async
函数中是一样的——如果我将锁获取未来放在foo
未来之前,它将立即有效地运行,并且锁将一直持有直到foo
真正开始的持续时间。
Is changing the body of foo
the only way or is there a workaround I'm not seeing?改变
foo
的主体是唯一的方法还是有我没有看到的解决方法?
To be a little more specific in case it sheds light, my situation is actually that foo
is the get
method of an asyncio.Queue
instance.更具体一点,以防万一,我的情况实际上是
foo
是asyncio.Queue
实例的get
方法。 Therefore it may be enough to subclass and override this one-line method with a two-line one that does my desired lock acquisition first.因此,将这个单行方法子类化并用一个两行方法覆盖它可能就足够了,该方法首先执行我想要的锁获取。 Or monkeypatch the method on the instance.
或者 monkeypatch 实例上的方法。 But this seems to be getting into ugly territory.
但这似乎进入了丑陋的领域。
https://github.com/python/cpython/blob/1e1dbdf23f7a18f53a3257badc3541973831f2c4/Lib/asyncio/queues.py#L57-L58 https://github.com/python/cpython/blob/1e1dbdf23f7a18f53a3257badc3541973831f2c4/Lib/asyncio/queues.py#L57-L58
Updated after comment.评论后更新。
In general, when using locks you should hold them for the shortest duration possible .通常,在使用锁时,您应该将它们持有的时间尽可能短。
Writing a subclass is probably the way to go if you need to use locks. go如果需要用到锁的话,写个子类大概是个办法。
Your question doesn't contain enough detail to give other sensible recommendations.您的问题没有包含足够的细节来提供其他明智的建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.