Search code examples
pythontornado

Coroutines with External Functions


I am trying to call a function inside a get request that is located in a separate .py file.

main.py

@gen.coroutine
def get(self):
    logging.info('starting TEST4: ' + str(datetime.now()))
    result = yield gen.Task(common.t2())
    print result
    logging.info('finished TEST4: ' + str(datetime.now()))
    self.write('complete!') 

common.py (external .py)

def t2():
    """ This is a non-blocking function """
    for x in range(10000000):
        for y in range(10):
            a = 1
    a = "Slow non-blocking function"
    return a   

I am trying to get the function t2 to run async and print the value of the variable "a" that it is returning. I am also running this code in Python 2.7 and that may also be an issue. What am I doing wrong?

Note: I also do not want to use the "concurrent.futures.ThreadPoolExecutor(8)" solution.


Solution

  • Despite its comments, t2 is a blocking function, as are all functions that don't use callbacks or yield. And there's no useful way to make t2 non-blocking, since it doesn't depend on any external events. Since t2 must block whatever thread it is called on, the only way to call it without blocking the main IOLoop thread is to call it on some other thread, and the best way to do that is with a ThreadPoolExecutor.