Search code examples
pythontornado

Limit connections for particular view in Tornado


I have view that takes a lot of memory and is asynchronous. Can I limit count of connections simultaneously working inside handler function (like critical section with N max workers inside).

Is this possible in Tornado?

Like:

@tornado.web.asynchronous
def get(self):
    with critical_section(count=5):
    # some code

Thanks


Solution

  • Toro provides synchronization primitives similar to those found in the threading module for Tornado coroutines. You could use its BoundedSemaphore to gate entry to the handler body:

    # global semaphore
    sem = toro.BoundedSemaphore(5)
    
    @gen.coroutine
    def get(self):
        with (yield sem.acquire()):
            # do work