改用ThreadPoolExecutor
时间: 2023-07-07 18:44:27 浏览: 110
线程池ThreadPoolExecutor
5星 · 资源好评率100%
使用`ThreadPoolExecutor`同样可以获得进度条,具体实现步骤如下:
1. 导入必要的库
```python
import concurrent.futures
from tqdm import tqdm
```
2. 创建线程池
```python
pool = concurrent.futures.ThreadPoolExecutor(max_workers=4)
```
3. 定义任务函数
```python
def task(arg):
# 完成任务的代码
```
4. 提交任务并使用`tqdm`显示进度条
```python
results = []
tasks = [arg1, arg2, arg3, ...]
with tqdm(total=len(tasks)) as pbar: # 设置进度条的总长度
futures = [pool.submit(task, arg) for arg in tasks]
for future in concurrent.futures.as_completed(futures):
result = future.result()
results.append(result)
pbar.update(1) # 每完成一个任务,进度条加1
```
这样就可以在运行`ThreadPoolExecutor`线程池时获得进度条了。
阅读全文