有没有办法在龙卷风中“锁定”请求,直到某些事情完成?

时间:2014-05-24 05:22:37

标签: python tornado

当我说锁定时,我的意思是它切换到其他协同程序并切换回来直到某些工作完成。

代码将像这样写:

@waitUntil('myProcess')
@gen.coroutine
def query():
    do_query()


@waitUntil('myProcess')
@gen.coroutine
def process():
    result = yield do_myProcess(params)
    deal_result(result)

这是我的waitUntil基于答案toro.Lock。不保证是对的,需要测试。

import toro

_locks = {}

def getLock(key):
    if key not in _locks:
        _locks[key] = toro.Lock()
    return _locks[key]


def waitUntil(key):
    def wrapped(func):
        @gen.coroutine
        def wrapped2(*args,**kwargs):
            with (yield getLock(key).acquire()):
                result = yield func(*args,**kwargs)
            return result
        return wrapped2
    return wrapped

2 个答案:

答案 0 :(得分:1)

尝试为此目的而写的toro.Lock

lock = toro.Lock()

@gen.coroutine
def f():
   with (yield lock.acquire()):
       assert lock.locked()

   assert not lock.locked()

https://toro.readthedocs.org/en/stable/classes.html#lock

答案 1 :(得分:0)

从v4.2开始,龙卷风已锁定:https://www.tornadoweb.org/en/stable/locks.html

尝试锁定。锁定:

>>> lock = locks.Lock()
>>>
>>> async def f():
...    async with lock:
...        # Do something holding the lock.
...        pass
...
...    # Now the lock is released.

请参阅锁定文档:https://www.tornadoweb.org/en/stable/locks.html#tornado.locks.Lock