python使用ThreadPoolExecutor
时间: 2025-01-14 20:09:14 浏览: 40
### Python 中 `ThreadPoolExecutor` 使用方法
在 Python 中,`concurrent.futures` 模块提供了 `ThreadPoolExecutor` 类来简化多线程编程的任务提交和管理。通过该类可以方便地创建并行执行任务的线程池。
#### 创建线程池对象
要使用 `ThreadPoolExecutor` 需先导入相应的模块,并实例化一个 `ThreadPoolExecutor` 对象:
```python
from concurrent.futures import ThreadPoolExecutor, as_completed
executor = ThreadPoolExecutor(max_workers=5) # 设置最大工作线程数为5
```
#### 提交单个任务给线程池
可以通过调用 `submit()` 方法向线程池提交可调用对象(通常是函数),它会立即返回一个表示未来结果的对象——Future:
```python
def task(n):
return n * n
future = executor.submit(task, 10)
print(future.result()) # 输出: 100
```
#### 批量提交多个任务
如果需要一次性提交大量相似的任务,则可通过列表推导式批量构建这些任务,并利用 `as_completed` 函数迭代获取已完成的结果:
```python
futures = [executor.submit(task, i) for i in range(5)]
for future in as_completed(futures):
print(future.result())
```
以上代码将会打印出从 0 到 4 各自平方后的数值[^2]。
#### 关闭线程池
当不再有新的任务需要加入时应该关闭线程池以释放资源,在此之后不能再添加新任务到这个线程池里了;但是已经存在的任务仍然会被继续处理直到完成为止。
```python
executor.shutdown(wait=True) # wait参数指定是否等待所有已提交任务完成后才结束程序
```
阅读全文
相关推荐


















