python 多线程并行
时间: 2023-10-13 15:21:01 浏览: 40
Python 中实现多线程并行有两种方式:使用 threading 模块和使用 concurrent.futures 模块。下面分别介绍这两种方式的用法。
1. 使用 threading 模块
```python
import threading
def worker(num):
print('Worker %d started' % num)
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
```
上述代码中,我们定义了一个 worker 函数,接受一个整数参数 num,然后打印 "Worker num started" 的字符串。然后我们创建了一个空的线程列表 threads,循环 5 次,每次创建一个新的线程 t,将 worker 函数作为 target,参数为 i,然后将线程 t 添加到线程列表中,并启动线程。
2. 使用 concurrent.futures 模块
```python
import concurrent.futures
def worker(num):
print('Worker %d started' % num)
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
for i in range(5):
executor.submit(worker, i)
```
上述代码中,我们先定义了一个 worker 函数,与上述 threading 方式相同。然后我们使用 concurrent.futures 模块中的 ThreadPoolExecutor 类来创建一个线程池,最多同时运行 5 个线程。使用 with 语句,我们将 executor 对象作为上下文管理器,然后循环 5 次,每次使用 executor.submit() 方法来提交 worker 函数和参数 i 到线程池中。线程池会自动管理线程的创建和销毁。
在上述两种方法中,我们都使用了 worker 函数来模拟一个需要并行处理的任务。你可以将 worker 函数替换成你自己的任务代码。注意,在并行处理时需要注意线程安全问题,避免多个线程同时访问和修改同一个数据而导致错误。