網站首頁 編程語言 正文
1.Task對象的作用
可以將多個任務添加到事件循環當中,達到多任務并發的效果
2.如何創建task對象
asyncio.create_task(協程對象)
注意:create_task
只有在python3.7及以后的版本中才可以使用,就像asyncio.run()
一樣,
在3.7以前可以使用asyncio.ensure_future()
方式創建task對象
3.示例一(目前不推薦這種寫法)
async def func(): print(1) await asyncio.sleep(2) print(2) return "test" async def main(): print("main start") # python 3.7及以上版本的寫法 # task1 = asyncio.create_task(func()) # task2 = asyncio.create_task(func()) # python3.7以前的寫法 task1 = asyncio.ensure_future(func()) task2 = asyncio.ensure_future(func()) print("main end") ret1 = await task1 ret2 = await task2 print(ret1, ret2) # python3.7以后的寫法 # asyncio.run(main()) # python3.7以前的寫法 loop = asyncio.get_event_loop() loop.run_until_complete(main()) """ 在創建task的時候,就將創建好的task添加到了時間循環當中,所以說必須得有時間循環,才可以創建task,否則會報錯 """
4.示例2
async def func1(): print(1111) await asyncio.sleep(2) print(2222) return "test" async def main1(): print("main start") tasks = [ asyncio.ensure_future(func1()), asyncio.ensure_future(func1()) ] print("main end") # 執行成功后結果在done中, wait中可以加第二個參數timeout,如果在超時時間內沒有完成,那么pending就是未執行完的東西 done, pending = await asyncio.wait(tasks, timeout=1) print(done) #print(pending) # python3.7以前的寫法 loop = asyncio.get_event_loop() loop.run_until_complete(main1())
5.示例3(算是以上示例2的簡化版)
""" 方式二的簡化版,就是tasks中不直接添加task,而是先將協程對象加入到list中,在最后運行中添加 """ async def func2(): print(1111) await asyncio.sleep(2) print(2222) return "test" tasks = [ func2(), func2() ] # python3.7以前的寫法 loop = asyncio.get_event_loop() done, pending = loop.run_until_complete(asyncio.wait(tasks)) print(done) print(pending)
總結
原文鏈接:https://blog.csdn.net/myli_binbin/article/details/123380985
相關推薦
- 2022-06-28 python生成圖片驗證碼的方法_python
- 2022-08-07 Go?Grpc?Gateway兼容HTTP協議文檔自動生成網關_Golang
- 2022-07-27 Python中的sys模塊、random模塊和math模塊_python
- 2022-04-07 C++?string與int的相互轉換(使用C++11)_C 語言
- 2023-03-22 gin正確多次讀取http?request?body內容實現詳解_Golang
- 2022-09-24 python?繪制3D圖案例分享_python
- 2022-07-08 C#中Lambda表達式的用法_C#教程
- 2022-07-09 Python實現功能全面的學生管理系統_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支