用协程实现高并发I/O(async)
对于并发要求比较法的I/O需求,可以用python的协程去处理。
重点:
1启动协程必须做一次函数调用
2协程激活只占用1kb内存,所以协程很多也问题不大
3这种效果需要使用关键字async和await
4协程和进程的区别在于:他不会从头到尾执行完,而是在遇到await表达式就暂停一次,下次继续执行的时候,他会等async操作有了结果,在推进下去
5python可以使用多async,让看起来像多线程并发(python由于GIL的原因其实不太支持做真正的并发)
import asyncio async def print_num(num): print("Maoli is printing " + str(num) + " nows" ) await asyncio.sleep(1) print("Maoli prints" + str(num) + " OK") async def main(nums): for num in nums: await print_num(num) asyncio.run(main([i for i in range(1,6)]))
Maoli is printing 1 nows Maoli prints1 OK Maoli is printing 2 nows Maoli prints2 OK Maoli is printing 3 nows Maoli prints3 OK Maoli is printing 4 nows Maoli prints4 OK Maoli is printing 5 nows Maoli prints5 OK
作者: yetangjian
出处: https://www.cnblogs.com/yetangjian/p/15850466.html
关于作者: yetangjian
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 可邮件(yetangjian@outlook.com)咨询.