asyncio cancel取消协程
task 是协程和 Future 的桥梁。
# coding=utf-8import asyncio
import time# 协程中是不能使用同步阻塞编程的
async def get_html (url):print('start get url', url)await asyncio.sleep(2)print('end get url')async def get_html2 (url):print('start get url', url)await asyncio.sleep(4)print('end get url')if __name__ == '__main__':start_time = time.time()loop = asyncio.get_event_loop()t1 = [get_html('www.baidu.com') for i in range(10)]t2 = [get_html2('www.google.com') for i in range(10)]try:# loop.run_until_complete(asyncio.wait(t1 + t2))loop.run_until_complete(asyncio.gather(*t1, *t2))except KeyboardInterrupt:for task in asyncio.Task.all_tasks():print(task.cancel())loop.stop()print('times', time.time() - start_time)
输出:
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
times 4.003652095794678
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
