赞
踩
asyncio中的wait和gather的用处和区别
wait等待协程执行完成后才会执行下一句
import asyncio
async def get_html(url):
print(f'start get {url}')
await asyncio.sleep(2)
print(f'end get {url}')
if __name__ == '__main__':
loop = asyncio.get_event_loop()
tasks = [get_html("https://www.baidu.com") for i in range(10)]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
gather的用法和区别
import asyncio async def get_html(url): print(f'start get {url}') await asyncio.sleep(2) print(f'end get {url}') if __name__ == '__main__': loop = asyncio.get_event_loop() group1 = [get_html("https://www.baidu.com") for i in range(10)] group2 = [get_html("https://www.google.com") for i in range(8)] group1 = asyncio.gather(*group1) group2 = asyncio.gather(*group2) loop.run_until_complete(asyncio.gather(group1, group2)) loop.close()
gather更加high-level,gather可以将tasks分组
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。