asyncio 协程函数

1.第一种写法

import asyncio
from time import time
async def fun(name):
    print(name, "1========")
    await asyncio.sleep(3)
    print(name,"2======")
    rest = name + '返回值'
    return rest

async def fun_1(name):
    print(name, "1=================")
    await asyncio.sleep(3)
    print(name, '2============')
    rest = name + '返回值'
    return rest

async def main():
    start_time = time()
    print('main 开始')
    # task1 = asyncio.create_task(fun('task1'))
    # task2 = asyncio.create_task(fun('task2'))
    # task3 = asyncio.create_task(fun_1('task3'))


    task_list = [
        asyncio.create_task(fun('task1'), name='task1'),
        asyncio.create_task(fun('task2'), name='task2'),
        asyncio.create_task(fun_1('task3'), name='task3')
    ]

    print('main结束')

    # rest1 = await task1
    # rest2 = await task2
    # rest3 = await task3
    done, pending = await asyncio.wait(task_list, timeout=None)
    print('done=======', done)
    end_time = time()
    print("time_total=====", end_time-start_time)
    # print(rest1, rest2, rest3)

asyncio.run(main())

2.第二种写法

async def fun(name):
    print(name, "1========")
    await asyncio.sleep(1)
    print(name,"2======")
    rest = name + '返回值'
    return rest

async def fun_1(name):
    print(name, "1=================")
    await asyncio.sleep(1)
    print(name, '2============')
    rest = name + '返回值'
    return rest

task_list = [
    fun("task1"),
    fun('task2'),
    fun_1('task3')
]

start_time = time()
done, pending = asyncio.run(asyncio.wait(task_list))
end_time = time()
print('total time=======', end_time-start_time)
print('done==', done)
print('type====', type(done))
print('pending===', pending)
for index, i in enumerate(done):
    print('index===', index, '\n', 'i======', i, '\n', 'type(i)===', type(i), '\n', 'reult====', i.result(), '\n')
end_time = time()
print('total time=======', end_time-start_time)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值