码迷,mamicode.com
首页 > 其他好文 > 详细

【12.2】task取消和子协程调用原理

时间:2019-08-17 19:46:34      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:mat   inter   oar   get   ctr   png   取消   pre   tin   

task取消

 1 import asyncio
 2 import time
 3 
 4 
 5 async def get_html(sleep_time):
 6     print(waiting)
 7     await asyncio.sleep(sleep_time)
 8     print(done after {}s.format(sleep_time))
 9 
10 
11 if __name__ == __main__:
12     task1 = get_html(2)
13     task2 = get_html(3)
14     task3 = get_html(3)
15 
16     tasks = [task1, task2, task3]
17 
18     loop = asyncio.get_event_loop()
19 
20     try:
21         loop.run_until_complete(asyncio.gather(*tasks))
22     except KeyboardInterrupt as e:
23         # KeyboardInterrupt 是按Ctrl+C终止程序时抛出的异常
24         # 获取所有的task
25         all_tasks = asyncio.Task.all_tasks()
26         for task in all_tasks:
27             print(cancel task)
28             print(task.cancel())
29         loop.stop()
30         loop.run_forever()
31     finally:
32         loop.close()
waiting
waiting
waiting
cancel task
True
cancel task
True
cancel task
True

 

 

技术图片

技术图片

 

【12.2】task取消和子协程调用原理

标签:mat   inter   oar   get   ctr   png   取消   pre   tin   

原文地址:https://www.cnblogs.com/zydeboke/p/11369709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!