协程:
实现方式:
1:greenlet 早期模块
2:yield关键字
3:asyncio装饰器 p3.4
4:async await p3.5
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() # 第一步,执行func1
# 1
# 3
# 2
# 4
yield 实现协程
# 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
# 4
# 2
asyncio 遇到io操作自动切换
coroutine过期了
import asyncio
@asyncio.coroutine
def func1():
print(1)
yield from asyncio.sleep(1)
print(2)
@asyncio.coroutine
def func2():
print(3)
yield from asyncio.sleep(2)
print(4)
tasks = [
asyncio.ensure_future(func1()),
asyncio.ensure_future(func2()),
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
import asyncio
async def func1():
print(1)
await asyncio.sleep(1)
print(2)
async def func2():
print(3)
await asyncio.sleep(2)
print(4)
tasks = [
asyncio.ensure_future(func1()),
asyncio.ensure_future(func2()),
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
原文:https://www.cnblogs.com/lzjloveit/p/14162322.html