1.使用greenlet
pip install greenlet
from greenlet import greenlet
def func1():
print(11)
g2.switch()
print(33)
g2.switch()
def func2():
print(22)
g1.switch()
print(44)
g1 = greenlet(func1)
g2 = greenlet(func2)
g1.switch()
2.使用yield关键字
def func3():
yield 1
yield from func4()
yield 4
def func4():
yield 2
yield 3
for i in func3():
print(i)
3.使用asyncio
# 在python3.5以下,也就是python3.4中的书写方式,因为asyncio是在python3.4中才引入的
import asyncio
# 3.1 使用asyncio的第一种书写格式
@asyncio.coroutine
def func5():
print(11111)
yield from asyncio.sleep(2)
print(2222222)
@asyncio.coroutine
def func6():
print(3333)
yield from asyncio.sleep(2)
print(444444)
tasks = [
asyncio.ensure_future(func5()),
asyncio.ensure_future(func6())
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
# 在python3.5以后的书写方式(去掉了装饰器,改为async和await)
async def func7():
print("abc")
await asyncio.sleep(2)
print("def")
async def func8():
print("hig")
await asyncio.sleep(2)
print("klm")
tasks2 = [
asyncio.ensure_future(func7()),
asyncio.ensure_future(func8())
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks2))
注:在python3.7以后,asyncio简化了一些方法,比如最后的启动方法,实际上就是封装了:
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks2))
以上在3.7中改为了:
asyncio.run(tasks2)