协程(异步)
python中为了提高I/O效率,使用协程去处理异步程序,协程自动完善了上述的各种调度任务!
- 进程和线程是计算机提供的,协程是程序员创造的,不存在于计算机中。
- 协程(
Co-routine
),也可称为微线程,或非抢占式的多任务子例程,一种用户态的上下文切换技术(通过一个线程实现代码块间的相互切换执行) - 意义:在一个线程(协程)中,遇到io等待时间,线程可以利用这个等待时间去做其他事情。
async
- 协程函数:定义函数时加上async修饰,即async def func()
- 协程对象:执行协程函数得到的对象
注:执行协程函数得到协程对象,函数内部代码不会执行
# python 源码
>>> import asyncio
>>> async def main():
... print('hello')
... await asyncio.sleep(1)
... print('world')
>>> main()
<coroutine object main at 0x1053bb7c8>
>>> asyncio.run(main())
hello
world
- 执行协程函数内部代码,必须把协程对象交给事件循环处理
await
- await + 可等待对象(协程对象,Future,Task对象(IO等待))
- 等待到对象的返回结果,才会继续执行后续代码
# python 源码
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f"started at {time.strftime('%X')}")
await say_after(1, 'hello')
#await say_after(1, 'hello')执行完之后,才继续向下执行
await say_after(2, 'world')
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
asyncio.create_task()
- asyncio.create_task()作为异步并发运行协程的函数Tasks。
- 将协程添加到asyncio.create_task()中,则该协程将很快的自动计划运行
# python 源码
async def main():
task1 = asyncio.create_task(
say_after(1, 'hello'))
task2 = asyncio.create_task(
say_after(2, 'world'))
print(f"started at {time.strftime('%X')}")
# Wait until both tasks are completed (should take around 2 seconds.)
# 两个任务同时执行,直到到所有任务执行完成。
await task1
await task2
print(f"finished at {time.strftime('%X')}")
原文链接:https://blog.csdn.net/qq_43380180/article/details/111573642