首页 > 编程语言 > 详细

python 协程

时间:2020-12-20 10:43:59      阅读:31      评论:0      收藏:0      [点我收藏+]


协程:
实现方式:
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))


python 协程

原文:https://www.cnblogs.com/lzjloveit/p/14162322.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!