Skip to content

Instantly share code, notes, and snippets.

@mangosmoothie
Created April 26, 2019 05:51
Show Gist options
  • Save mangosmoothie/9de46f17bf783e2db07120657c5b466f to your computer and use it in GitHub Desktop.
Save mangosmoothie/9de46f17bf783e2db07120657c5b466f to your computer and use it in GitHub Desktop.
Tornado Coroutines with Locks
import tornado.web
from tornado import gen
from tornado.locks import Lock
class Service():
def __init__(self, service_id, nth=None):
self._nth = nth
self._service_id = service_id
self._count = 0
self._lock = Lock()
print('starting class', service_id)
async def do_work(self):
async with self._lock:
self._count += 1
print('%s starting work %s' % (self._service_id, self._count))
if self._nth and not self._count % self._nth:
print('%s sleeping work %s' %
(self._service_id, self._count))
await gen.sleep(3)
print('%s done with work %s' %
(self._service_id, self._count))
return self._count
s1 = Service(1, 2)
s2 = Service(2)
class Handler(tornado.web.RequestHandler):
async def get(self):
r1, r2 = await gen.multi([s1.do_work(), s2.do_work()])
self.write("s1: {:<4} s2: {:<4}".format(r1, r2))
if __name__ == "__main__":
app = tornado.web.Application(
[
(r"/", Handler),
],
)
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment