Python 实现异步并发多线程
时间: 2023-06-29 09:05:58 浏览: 66
在 Python 中,实现异步并发多线程的方式有很多,其中比较流行的是使用 asyncio 和 threading 库。
使用 asyncio 实现异步并发多线程:
```python
import asyncio
async def worker():
print('Worker start')
await asyncio.sleep(1)
print('Worker end')
async def main():
tasks = [worker() for _ in range(5)]
await asyncio.gather(*tasks)
if __name__ == '__main__':
asyncio.run(main())
```
上面的代码中,我们定义了一个异步函数 `worker`,它会打印一条信息,等待 1 秒钟,然后再打印一条信息。接着,我们定义了一个 `main` 函数,该函数创建了 5 个 `worker` 任务,并使用 `asyncio.gather` 将它们收集起来,等待它们全部完成。
使用 threading 库实现异步并发多线程:
```python
import threading
import time
def worker():
print('Worker start')
time.sleep(1)
print('Worker end')
if __name__ == '__main__':
threads = [threading.Thread(target=worker) for _ in range(5)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
```
上面的代码中,我们定义了一个函数 `worker`,它会打印一条信息,等待 1 秒钟,然后再打印一条信息。接着,我们创建了 5 个线程,并将 `worker` 函数作为每个线程的目标函数。最后,我们启动所有线程,并等待它们全部完成。