在以下代码示例中,展示了如何使用异步/等待操作并行执行多个任务。
import asyncio
async def task1():
print("开始执行任务1")
await asyncio.sleep(1)
print("任务1完成")
async def task2():
print("开始执行任务2")
await asyncio.sleep(2)
print("任务2完成")
async def task3():
print("开始执行任务3")
await asyncio.sleep(3)
print("任务3完成")
async def main():
# 创建一个事件循环
loop = asyncio.get_event_loop()
# 并行执行多个任务
await asyncio.gather(
task1(),
task2(),
task3()
)
# 关闭事件循环
loop.close()
# 运行主程序
asyncio.run(main())
在上述示例中,我们定义了三个任务(task1、task2、task3),它们分别模拟了耗时的操作(使用asyncio.sleep
来模拟)。然后,我们使用asyncio.gather
函数并行执行这些任务。
通过使用asyncio.run
函数,我们可以运行主程序。在主程序中,我们创建了一个事件循环,然后使用asyncio.gather
来并行执行所有任务。最后,我们关闭事件循环。
运行上述代码,将会看到任务1、任务2和任务3按照并行的方式执行,而不是按照顺序执行。
上一篇:并行执行的CPU性能分析
下一篇:并行执行对象列表