python同时运行两个循环
时间: 2024-01-18 21:49:50 浏览: 26
可以使用多线程或者协程来实现同时运行两个循环。
使用多线程的话,可以使用Python内置的`threading`模块,具体实现如下:
```python
import threading
def loop1():
while True:
print('Loop1')
def loop2():
while True:
print('Loop2')
t1 = threading.Thread(target=loop1)
t2 = threading.Thread(target=loop2)
t1.start()
t2.start()
```
使用协程的话,可以使用Python的`asyncio`模块,具体实现如下:
```python
import asyncio
async def loop1():
while True:
print('Loop1')
await asyncio.sleep(1)
async def loop2():
while True:
print('Loop2')
await asyncio.sleep(1)
async def main():
task1 = asyncio.create_task(loop1())
task2 = asyncio.create_task(loop2())
await asyncio.gather(task1, task2)
asyncio.run(main())
```
以上代码中,`loop1`和`loop2`函数都是无限循环,分别输出`Loop1`和`Loop2`。使用多线程或协程,可以使它们同时运行,无需等待一个循环结束再运行另一个循环。