用协程实现高并发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

 

posted @ 2022-01-27 17:05  yetangjian  阅读(109)  评论(0编辑  收藏  举报