简体   繁体   中英

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. 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?

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() .

Which request will acquire the lock first?

The first that called 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. However, it is not deadlock, setting timeout in acquire is very helpful. 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.

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