python 同时执行多个携程
时间: 2023-07-06 17:39:51 浏览: 71
可以使用协程库 asyncio 来实现 Python 中的多协程并发执行。使用 asyncio 库,可以使用 async/await 语法来定义协程函数,使用 asyncio.create_task() 函数来创建任务,并使用 asyncio.gather() 函数来并发执行多个任务。
下面是一个简单的示例代码,用于同时执行多个协程:
```python
import asyncio
async def coroutine1():
print('Coroutine 1 started')
await asyncio.sleep(1)
print('Coroutine 1 ended')
async def coroutine2():
print('Coroutine 2 started')
await asyncio.sleep(2)
print('Coroutine 2 ended')
async def coroutine3():
print('Coroutine 3 started')
await asyncio.sleep(3)
print('Coroutine 3 ended')
async def main():
task1 = asyncio.create_task(coroutine1())
task2 = asyncio.create_task(coroutine2())
task3 = asyncio.create_task(coroutine3())
await asyncio.gather(task1, task2, task3)
asyncio.run(main())
```
在上面的示例代码中,我们定义了 3 个协程函数 coroutine1()、coroutine2() 和 coroutine3(),然后在 main() 函数中使用 asyncio.create_task() 函数创建了 3 个任务,并使用 asyncio.gather() 函数并发执行这 3 个任务。最后,我们使用 asyncio.run() 函数来运行 main() 函数。执行上述代码后,将会输出如下结果:
```
Coroutine 1 started
Coroutine 2 started
Coroutine 3 started
Coroutine 1 ended
Coroutine 2 ended
Coroutine 3 ended
```