Python 龙卷风协同程序的问题。不';不能异步运行
经过几次痛苦的尝试,我写了这样的东西:Python 龙卷风协同程序的问题。不';不能异步运行,python,asynchronous,tornado,yield,coroutine,Python,Asynchronous,Tornado,Yield,Coroutine,经过几次痛苦的尝试,我写了这样的东西: urls=[ 'http://localhost', 'http://www.baidu.com', 'http://www.taobao.com', 'http://www.163.com', 'http://www.sina.com', 'http://www.qq.com', 'htt
urls=[
'http://localhost',
'http://www.baidu.com',
'http://www.taobao.com',
'http://www.163.com',
'http://www.sina.com',
'http://www.qq.com',
'http://www.jd.com',
'http://www.amazon.cn',
]
@tornado.gen.coroutine
def fetch_with_coroutine(url):
response=yield tornado.httpclient.AsyncHTTPClient().fetch(url)
print url,len(response.body)
raise tornado.gen.Return(response.body)
@tornado.gen.coroutine
def main():
for url in urls:
yield fetch_with_coroutine(url)
timestart=time.time()
tornado.ioloop.IOLoop.current().run_sync(main)
print 'async:',time.time()-timestart
但它甚至比同步代码慢一点。此外,输出的顺序总是相同的,因此我认为它不会异步运行。
我的代码出了什么问题?在main()
中,您正在调用fetch\u with\u corroutine
一次调用一个;您使用yield
的方式意味着在第一次提取完成之前,第二次提取无法开始。相反,您需要首先启动它们,然后以单一收益率等待它们:
@gen.coroutine
def main():
# 'fetches' is a list of Future objects.
fetches = [fetch_with_coroutine(url) for url in urls]
# 'responses' is a list of those Futures' results
# (i.e. HTTPResponse objects).
responses = yield fetches