python异步IO编程(二)
目录
开门见山
Async IO设计模式
事件循环
asyncio 中的其他顶层函数
开门见山
下面我们用两个简单的例子来让你对异步IO有所了解
importasyncio
asyncdefcount():print("One")
await asyncio.sleep(1)print("Two")
asyncdefmain():
await asyncio.gather(count(),count(),count())if __name__ =="__main__":importtime
start_time=time.time()
asyncio.run(main())
end_time=time.time()print("执行时间:%s" %(end_time-start_time)+"秒")
运行结果:
One
One
One
Two
Two
Two
执行时间:1.0010051727294922秒
这个输出的顺序是异步IO的核心,由单一事件循环或协调器负责与每一个 count() 方法调用交流。当每一个任务执行到 await asyncio.sleep(1)) 时,函数会通知事件循环并交出控制权限,“我要睡眠一秒钟,在此期间,继续做其他有意义的事”(其他协程)。
与同步的版本对比:
defcount():print("One")
time.sleep(1)print("Two")defmain():for _ in range(3):
count()if __name__ =="__main__":importtime
start_time=time.time()
main()
end_time=time.time()print("执行时间:%s" %(end_time-start_time)+"秒")
运行结果:
One
Two
One
Two
One
Two
执行时间:3.001182794570923秒
使用 time.sleep() 和 asyncio.sleep() 看起来有点简陋,这里一般用来替代标准输入等耗时的操作。(最简单的等待就是使用 sleep(),基本上什么也不做。)也就是说 time.sleep() 可以表示任何耗时的阻塞函数的调用,而 asyncio.sleep() 用于表示非阻塞的函数调用(但是也是需要一定时间来完成)。
异步i