为什么两个顺序协程(异步函数)并行执行?

时间:2016-04-24 23:10:27

标签: python-3.x asynchronous tornado

所以,我只是试图围绕异步编程(特别是Tornado框架),并认为我从基础知识开始:在两个协同程序上调用“等待”:

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的两个交织序列,而是两个连续序列。

我已经一遍又一遍地阅读了龙卷风FAQ,似乎无法理解我做错了什么。

2 个答案:

答案 0 :(得分:3)

运行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 ,然后再回来等待它:

plot.title = "Some string"

答案 1 :(得分:0)

并行 - official example

multi 函数接受值为 Futures 的列表和字典,并并行等待所有这些 Futures

from tornado.gen import multi

async def parallel_fetch(url1, url2):
    resp1, resp2 = await multi([http_client.fetch(url1),
                                http_client.fetch(url2)])

async def parallel_fetch_many(urls):
    responses = await multi ([http_client.fetch(url) for url in urls])
    # responses is a list of HTTPResponses in the same order

async def parallel_fetch_dict(urls):
    responses = await multi({url: http_client.fetch(url)
                             for url in urls})
    # responses is a dict {url: HTTPResponse}