python 中的协程其实就是一种高效的任务切换模式: 遇到需要等待的(例如io等待), 直接跳到其他任务去执行,不会傻傻的等到io结束才向下执行 先看一个如果没有异步的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import asyncio import time def func1(): print("this is func1 ") time.sleep(2) print("this is end of func1") def func2(): print("this is func2 ") time.sleep(2) print("this is end of func2") if __name__ == '__main__': func1() func2() |
运行结果:
1 2 3 4 5 |
this is func1 this is end of func1 this is func2 this is end of func2 python asyntest.py 0.06s user 0.02s system 1% cpu 4.105 total |
也就是说,我们如果……