Python——协程操作async
2021/12/13 9:17:32
本文主要是介绍Python——协程操作async,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
简介
协程就是CPU中断
效果上类似生成器函数,yield会记录迭代位置和状态然而会中断执行。
关键字
python中Async模块实现协程操作。
Aysnc:定义协程函数。
await:挂起支持异步的操作
使用
async def p1(): print("比利1") await asyncio.sleep(5) print("比利2") async def p2(): print("van1") await asyncio.sleep(5) print("van2") async def p3(): print("hello1") await asyncio.sleep(5) print("hello2") def main(): loop = asyncio.get_event_loop() task = [ loop.create_task(p1()), loop.create_task(p2()), loop.create_task(p3()) ] loop.run_until_complete(asyncio.wait(task)) if __name__ == '__main__': main()
总结
单线程协程操作 1.async标记协程函数 2.await标记支持异步的阻塞方法 3.通过循环器生成任务列表,执行
这篇关于Python——协程操作async的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python