简体   繁体   English

用协程获得龙卷风锁

[英]Acquiring Tornado Locks with coroutine

Take this code as an example. 以此代码为例。

from tornado import gen, locks
lock = locks.Lock()

@gen.coroutine
def f():
    while True:
        with (yield lock.acquire()):
            # Do something holding the lock.
            pass
        # Now the lock is released.
        yield gen.sleep(0.5)

Say I have a coroutine that runs every second in an infinite loop which has some global variables which cannot be changed until the routine is finished. 假设我有一个协程,它在无限循环中每秒运行一次,该循环具有一些全局变量,这些常规变量在例程完成之前无法更改。

I have several http requests while this routine is busy processing. 这个例程忙于处理时,我有几个http请求。 All these requests are waiting to acquire the lock. 所有这些请求都在等待获取锁。 Which request will acquire the lock first, and is it possible that they might deadlock where both are trying to acquire the lock at the same time? 哪个请求将首先获取锁,并且在两个试图同时获取锁的地方,它们是否可能死锁?

Would a lock queue system not be a better option where a list of waiting requests are added so you have a FIFO queue, or is this not necessary? 锁定队列系统不是一个更好的选择,在该列表中添加了一个等待请求列表,以便您拥有一个FIFO队列,或者这不是必需的吗?

If two requests try to acquire the lock at the same time, one of them will win. 如果两个请求尝试同时获取锁,则其中一个将获胜。 There is no possibility for a deadlock with a single lock. 单锁死锁是不可能的。 Tornado's Lock uses a queue internally, so the waiting requests will acquire the lock in the order they called acquire() . 龙卷风的Lock在内部使用队列,因此,等待的请求将按其称为acquire()的顺序获取锁。

Which request will acquire the lock first? 哪个请求将首先获取锁?

The first that called acquire (FIFO) 第一个称为acquire (FIFO)

is it possible that they might deadlock where both are trying to acquire the lock at the same time 他们是否有可能在试图同时获取锁的地方陷入僵局

The next will wait until previous unlocks. 下一个将等待,直到上一个解锁。 If you bother about the same time , tornado.locks meant to be only for single threaded apps, so it is not possible. 如果您在同一时间打扰, tornado.locks意味着仅适用于单线程应用程序,因此这是不可能的。 However, it is not deadlock, setting timeout in acquire is very helpful. 但是,它不是死锁,在acquire设置timeout非常有帮助。 Imagine that routine locks and then fetch data for high-loaded server (or waits for another lock), rest of the waiters might wait too long or even infinitely. 想象一下,例行锁定然后为高负载服务器获取数据(或等待另一个锁定),其余的等待者可能等待太长时间甚至无限期。

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

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