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