Python3协程示例

1、函数协程

import asyncio
import time


# 定义一个异步函数,模拟异步任务
async def task(number):
    print(f"Task {number} started; time:{time.ctime()}")
    await asyncio.sleep(1)
    print(f"Task {number} finished ; time:{time.ctime()}")


async def main():
    tasks = []
    for i in range(1, 6):         # 开启五个携程
        task_instance = task(i)
        tasks.append(task_instance)

    await asyncio.gather(*tasks)  # 并行运行多个协程

if __name__ == "__main__":
    asyncio.run(main())

Result:
D:\pythonProject\venv\Scripts\python.exe D:/pythonProject/test.py
Task 1 started; time:Mon Oct 23 17:15:09 2023
Task 2 started; time:Mon Oct 23 17:15:09 2023
Task 3 started; time:Mon Oct 23 17:15:09 2023
Task 4 started; time:Mon Oct 23 17:15:09 2023
Task 5 started; time:Mon Oct 23 17:15:09 2023
Task 1 finished ; time:Mon Oct 23 17:15:10 2023
Task 3 finished ; time:Mon Oct 23 17:15:10 2023
Task 5 finished ; time:Mon Oct 23 17:15:10 2023
Task 2 finished ; time:Mon Oct 23 17:15:10 2023
Task 4 finished ; time:Mon Oct 23 17:15:10 2023
 
Process finished with exit code 0

 

2、类协程

import asyncio


class AsyncClass:
    def __init__(self):
        pass

    async def async_method(self, name):
        await asyncio.sleep(1)
        print(f"Hello, {name}!")

    async def run_async_methods(self):
        tasks = [self.async_method("Alice"), self.async_method("Bob")]
        await asyncio.gather(*tasks)


if __name__ == "__main__":
    async_class = AsyncClass()
    asyncio.run(async_class.run_async_methods())

Result:
D:\pythonProject\venv\Scripts\python.exe D:/pythonProject/test.py
Hello, Alice!
Hello, Bob!
 
Process finished with exit code 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值