Search code examples
pythontornado

Is there a way to "lock" requests in tornado until something is done?


when i say lock ,i mean it switch to other coroutines and switch back until certain work is done.

the code would be write like these:

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


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

here's my waitUntil based on the answer toro.Lock. don't guarantee it is right,need test.

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

Solution

  • Try toro.Lock, which I wrote for this purpose

    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