python 3.x - Why don't two sequential coroutines (async functions) execute in parallel? -
so, i'm trying wrap head around async programming (in particular tornado framework), , thought i'd start basics: calling "awaiting" on 2 coroutines:
from tornado.ioloop import ioloop tornado.web import application, url, requesthandler tornado.gen import sleep class testhandler(requesthandler): async def get(self): f1 = await self.test("f1") f2 = await self.test("f2") self.write(f1 + " " + f2) async def test(self, msg): in range(5): print(i) await sleep(1) # tornado's async sleep return msg app = application([url(r'/', testhandler)], debug=true) app.listen(8080) ioloop = ioloop.current() ioloop.start()
the issue, however, when hit localhost:8080
in browser, , stare @ python console, don't see 2 interwoven sequences of 0 1 2 3 4
, 2 sequential sequences...
i've read tornado faq over-and-over again , can't seem understand i'm doing wrong.
this runs f1
, waits finish, runs f2
:
f1 = await self.test("f1") f2 = await self.test("f2")
to run things in parallel, can't await
first 1 before starting second. simplest way them both in 1 await
:
f1, f2 = await tornado.gen.multi(self.test("f1"), self.test("f2"))
or in advanced cases, can start f1
without waiting come wait later:
f1_future = tornado.gen.convert_yielded(self.test("f1")) f2_future = tornado.gen.convert_yielded(self.test("f2")) f1 = await f1_future f2 = await f2_future
Comments
Post a Comment