python协程

一、术语
1、coroutine func:用async def定义的函数
2、coroutine object:调用coroutine func生成
3、task:coroutine object在eventloop即为task
4、await一个coroutine object就会将此object注册为task,并且此task在eventloop需要优先执行,然后返回函数的返回值
5、async模式:eventloop控制task执行,对应sync模式,进入的唯一入口是asyncio.run(),其参数是coroutine object
6、eventloop开启task后,只有task函数执行完成或者await之后才能再次拿到执行权,故此协程不存在数据竞争
二、代码
1

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f'start at {time.strftime('%X')}')

    await say_after(1, 'hello') # ,
    '''
    1、corountine对象变成task加入eventloop
    2、在eventloop中此task优先于调用者task(此处为main)
    3、yield出去,eventloop重新得到控制权,并且立即执行刚创建的task(此处为say_after)
    4、say_after执行完毕后返回函数的返回值
    '''
    await say_after(2, 'world')

    print(f'end at {time.strftime('%X')}')

corountine_object = main()
asyncio.run(corountine_object)

2

import asyncio
import time


async def say_after(delay, what):
    await asyncio.sleep(delay)
    return f'{what}-{delay}'

async def main():

    task1 = asyncio.create_task(say_after(2, 'hello'))
    task2 = asyncio.create_task(say_after(1, 'world'))

    print(f'start at {time.strftime('%X')}')
    ret1 = await task1
    ret2 = await task2
    print(ret1)
    print(ret2)
    print(f'end at {time.strftime('%X')}')

corountine_object = main()
asyncio.run(corountine_object)

3

import asyncio
import time


async def say_after(delay, what):
    await asyncio.sleep(delay)
    return f'{what}-{delay}'

async def main():

    task1 = asyncio.create_task(say_after(2, 'hello'))
    task2 = asyncio.create_task(say_after(1, 'world'))

    print(f'start at {time.strftime('%X')}')

    ret = await asyncio.gather(say_after(2, 'hello'), say_after(1, 'world'))
    '''
    1、gather参数可以是coroutine object、task、或者futher
    2、gather返回futher
    3、await futher和await coroutine object或者task类似
    '''
    print(ret)
    print(f'end at {time.strftime('%X')}')

corountine_object = main()
asyncio.run(corountine_object)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值