协程快速上手

"""
await关键字, await+(cortinue对象,future对象,task对象)  需要在等待的对象返回值以后,才能执行await之后的代码
await适用的场景时,await后面的代码会依赖 await等待的对象的返回值
"""

import asyncio

# 例1 await asyncio.sleep()
async def func(index):
    print("开始执行func{}".format(index))
    await asyncio.sleep(1)
    print("运行结束{}".format(index))

# 例2 await+ cortinue对象
async def other(index):
    print("other start {}".format(index))
    await asyncio.sleep(2)
    print("other end {}".format(index))

async def func2(index):
    print("func2 start {}".format(index))
    await other(index)
    print("func2 end {}".format(index))

# 例3 依赖await 返回值的
async def func3(index):
    print("func3 start {}".format(index))
    answer = await add(index)
    print("func3 end {}".format(answer))

async def add(index):
    print("add start {}".format(index))
    # await asyncio.sleep(2)
    print("add end {}".format(index))
    return 1+index

tasks = [ asyncio.ensure_future(func3(index))  for index in range(5)]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))



执行结果:

func3 start 0
add start 0
add end 0
func3 end 1
func3 start 1
add start 1
add end 1
func3 end 2
func3 start 2
add start 2
add end 2
func3 end 3
func3 start 3
add start 3
add end 3
func3 end 4
func3 start 4
add start 4
add end 4
func3 end 5

Process finished with exit code 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值