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")
关于运行协程的方式,我们就了解到这啦!
-
华为hcia是什么啊
很多朋友都想知道华为hcia是什么?下面就一起来了解一下吧!华为hcia的全称为Huawei Certified ICT Associate,意思是华为认证ICT工程师,是华为...
科技查看全文>> -
汽车痒传感器坏了表现
首先,是氧传感器,不是痒传感器,系错被子。坏了的表现:氧传感器中毒、油门积碳(大量冒黑烟)、发动机动力不足、加热器电阻丝烧断。一、氧传感器中毒。对于经常使用含铅汽油的车辆,氧传...
问答查看全文>> -
户外传媒哪个牌子好 户外传媒十大品牌排行榜
为您整理了户外传媒哪个牌子好,分别有航美传媒Airmedia、华视传媒、分众传媒、德高/JCDecaux、白马传媒、海峡彩亮、大贺传媒、巴士在线BUSAP、TOM户外、百灵时代...
品牌查看全文>>
推荐
- 12022开学朋友圈文案272
- 2钓鱼佬永不空军是什么意思346
- 3分动器是什么?178
- 4货车四轮定位怎么做?368
- 5带雄字的男孩名字343
- 6变速箱油不足报警吗?204
- 7道士十五狗是什么意思 道士15狗是什么意思248
- 8没有冰箱怎么保存鸡肉166