协程
当程序处于
- 等待输入
input()
- 等待请求响应
resquts.get()
- IO操作
线程会处于阻塞状态,cpu没有工作,于是我们可以选择切换到其他任务,避免浪费掉处于阻塞状态的时间
所以,协程只是使对单个线程的利用更充分了,并没有开辟新的线程,占据更多的资源
在宏观上是多任务并行的,在微观上是串行的
如何使用携程
我们需要导入asyncio
在定义方法时使用关键字async
表明这是一个异步函数
在方法中使用await asyncio.sleep()
来实现异步休眠,此时会告诉程序这个任务需要休眠,可以切换到其他任务
在调用这个方法时不会立即执行,而会返回一个对象
使用
asyncio.run()
运行协程对象
asyncio.wait()
封装协程对象,传入列表,返回协程对象
来调用它们
import asyncio
async def a():
print("hello world")
await asyncio.sleep(1)
print("hello world")
async def b():
print("hello python")
await asyncio.sleep(3)
print("hello python")
async def c():
print("hello django")
await asyncio.sleep(2)
print("hello django")
if __name__ == '__main__':
tasks = [
a(), b(), c()
]
asyncio.run(asyncio.wait(tasks))
![](https://img-blog.csdnimg.cn/1df068f77eab4cb3ab4345d42a9a51cc.png)
可以看到打印结果中三个方法是同时执行的
注意 await
只能在async
修饰的方法里使用,在后面跟一个协程对象,表示挂起这个对象
2023.3.23