2016-04-24 34 views
0

所以,我只是想换我周围的异步编程头(特别是龙卷风框架),我想我会从基础开始:调用“等待”两个协程:为什么两个连续的协程(异步函数)并行执行?

from tornado.ioloop import IOLoop 
from tornado.web import Application, url, RequestHandler 
from 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): 
     for i in range(5): 
      print(i) 
      await sleep(1) # this is tornado's async sleep 
     return msg 

app = Application([url(r'/', TestHandler)], debug=True) 
app.listen(8080) 
ioloop = IOLoop.current() 
ioloop.start() 

的然而,问题是,当我在浏览器中点击localhost:8080,并且在我的Python控制台盯着,我没有看到的0 1 2 3 4 2个交织序列,但两个连续的序列......

我读过的龙卷风FAQ一遍又一遍,似乎无法理解我做错了什么。

回答

2

这将运行f1,等待它完成,然后运行f2

f1 = await self.test("f1") 
    f2 = await self.test("f2") 

并行运行的东西,你不能await开始前一秒第一个。要做到这一点,最简单的方法是做他们两个在一个await

f1, f2 = await tornado.gen.multi(self.test("f1"), self.test("f2")) 

或者在先进的情况下,你就可以开始f1无需等待它,然后回来以后等待它:

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 
+0

第二个代码块(期待已久)不能同时运行......我误解了你,它不应该被期望吗? – StevieP

+0

啊,你说得对。这种模式使用'@ gen.coroutine'工作,但'async def'函数直到某些“等待”它们才开始。 –

+0

你介意解释最佳实践吗?看起来Tornado和'asyncio'(特别是'async' /'await')并没有真正的配合。我们应该如何去编写/装饰异步代码(因为我们想要使用Tornado)? – StevieP