Skip to content

Instantly share code, notes, and snippets.

@pauloalem
Created October 27, 2016 16:49
Show Gist options
  • Save pauloalem/c3a44ce6fbbde0128c7c7ccea92f2773 to your computer and use it in GitHub Desktop.
Save pauloalem/c3a44ce6fbbde0128c7c7ccea92f2773 to your computer and use it in GitHub Desktop.
Example of how to offload a blocking task in tornado using the threading module in python3
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
from tornado.gen import coroutine, Task
import threading
from time import sleep
def do_block(callback, args):
def _callback():
n, = args
print("oh")
sleep(n)
print("hay")
IOLoop.instance().add_callback(lambda: callback(n))
t = threading.Thread(target=_callback)
t.start()
class HandlerA(RequestHandler):
@coroutine
def get(self):
foo = yield Task(do_block, args=(3, ))
class HandlerB(RequestHandler):
def get(self):
self.write("oh hay")
self.finish()
HTTPServer(Application([
("/a", HandlerA),
("/b", HandlerB),
], debug=True)).listen(9999)
IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment