python asyncio
python协程库asyncio的运行方式有哪些?我们一起了解一下吧!
asyncio 是以协程的模式来编写并发的库,使用 async/await 语法。在 IO密集型 的网络编程里,异步IO 协程 省去了开辟新的线程和进程的开销。asyncio 是 Python3.4 版本引入到标准库,python3.5 加入了 async/await 特性。下面我们就来分享一下运行协程的几种方式。
使用 async 声明协程
async def asyncTask():
# 协程休眠
await asyncio.sleep(1)
print(time.strftime('%X'))
运行协程的几种方式:
1、asyncio.run() 函数用来在非协程函数中调用协程
asyncio.run(asyncTask())
2、使用 await 等待一个协程。
await asyncTask()
3、asyncio.create_task() 用函数将协程打包为一个 Task 排入日程准备执行,返回 asyncio.Task 对象。
此函数 在 Python 3.7 中被加入。
task1 = asyncio.create_task(asyncTask1())task2 = asyncio.create_task(asyncTask2())await task1await task2
4、使用 asyncio.gather() 函数来并发多个协程。
tasks = asyncio.gather(asyncTask1(), asyncTask2())tasks2 = asyncio.gather(*[asyncTask1(), asyncTask2()])await tasksawait tasks2
具体示例:
import asyncioimport time# 定义协程任务async def asyncTask1():
# 协程休眠
await asyncio.sleep(1)
print(time.strftime('%X'), 1)async def asyncTask2():
await asyncio.sleep(2)
print(time.strftime('%X'), 2)async def main():
task1 = asyncio.create_task(asyncTask1())
task2 = asyncio.create_task(asyncTask2())
tasks = asyncio.gather(asyncTask1(), asyncTask2())
tasks2 = asyncio.gather(*[asyncTask1(), asyncTask2()]) await tasks await tasks2 await task1 await task2
print(time.strftime('%X'), "start")
asyncio.run(main())
print(time.strftime('%X'), "end")
关于运行协程的方式,我们就了解到这啦!
-
科索发动机和上菲红怎么区分?
科索发动机和上菲红区分方法:1、科索发动机是一个单独的发动机产品;而上菲红是一个发动机品牌。2、科索发动机有着动力强劲、经济可靠、安全舒适、低碳环保等特点;而上菲红发动机的整体...
问答查看全文>> -
夏天为什么不能喝红茶
夏天并非不能喝红茶,茶为健康饮品,而红茶为全发酵茶,茶内物质丰富,红茶属性温和,但并非性燥,因此夏天也可以正常饮用,而且也能起到生津解渴,解暑的效果,但需要注意用量适当,不宜饮...
茶叶查看全文>> -
科目二补考预约不上什么原因?
科目二补考预约不上的原因:1、科目二考试不合格的,申请百人需要先向车管所缴纳补考费,然后间隔十度日以后可以重新预约补考的;2、科目二预约网上预约不成功的,申请人可以选择其它方法...
问答查看全文>> -
鼠年男孩起名字大全免费
鼠年男孩起名字有哪些?我们一起来看看吧!1、鼠年男孩起名字大全免费单字推荐01、老鼠在十二生肖中排名首位,所以可以选取带有“王”或与“王”有关的字。(琨)——“琨”中有“王”,...
生活查看全文>>
推荐
- 1p065F故障码解释和消除方法,P065F故障码怎么解决?160
- 2拎的清是什么意思 拎的清是什么梗280
- 3一个人的世界很安静的说说333
- 4QQ在哪里可以屏蔽群消息275
- 5驾照消分怎么算?173
- 6宝马318i二手车价格?187
- 7有关白鹅的歇后语476
- 8科目三挂科了怎么办?163