协程
- 异步非阻塞、asyncio
- 相关框架 tornado、fastapi、django3.x(asgi)、 aiohttp(爬虫) -> 提升性能
协程
协程不是计算机提供,人为创造
协程(Coroutine),也可以被称为微线程,是一种用户态内的上下文切换技术,简言之,其实就是通过一个线程实现代码块相互切换执行,例如
def func1():
print(1)
print(2)
def func2():
print(3)
print(4)
func1()
func2()
实现协程的集中方法:
- greenlet,早期模块
- yield 关键字
- asyncio 装饰器(python3.4)
- async、await 关键字 (python3.5)【推荐】
1.1 使用greenlet实现协程
pip install greenlet
from greenlet import greenlet
def func1():
print(1)
gr2.switch()
print(2)
gr2.switch()
def func2():
print(3)
gr1.switch()
print(4)
gr1 = greenlet(func1)
gr2 = greenlet(func2)
gr1.switch()
# 打印如下
"""
1
3
2
4
"""
1.2 yield关键字
def func1():
yield 1
yield from func2()
yield 2
def func2():
yield 3
yield 4
f1 = func1()
for item in f1:
print(item)
# 打印如下
"""
1
3
2
4
"""
1.3 asyncio模块
python3.4及以后
import asyncio
@asyncio.coroutine
def func1():
print(1)
# todo 网络io请求:下载一张图片
yield from asyncio.sleep(2)
print(2)
@asyncio.coroutine
def func2():
print(3)
# todo 网络io请求:下载一张图片
yield from asyncio.sleep(2)
print(4)
# 将两个协程函数打包到tasks中
tasks = [
asyncio.ensure_future(func1()),
asyncio.ensure_future(func2())
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
# 打印如下
"""
1
3
2
4
"""
遇到io阻塞自动切换
1.4 async & await 关键字
python3.5及之后的版本
import asyncio
async def func1():
print(1)
# todo 网络io请求:下载一张图片
await asyncio.sleep(2)
print(2)
async def func2():
print(3)
# todo 网络io请求:下载一张图片
await asyncio.sleep(2)
print(4)
# 将两个协程函数打包到tasks中
tasks = [
asyncio.ensure_future(func1()),
asyncio.ensure_future(func2())
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
# 打印如下
"""
1
3
2
4
"""

浙公网安备 33010602011771号