python ThreadPoolExecutor使用 举例
时间: 2024-04-08 21:27:51 浏览: 139
ThreadPoolExecutor是Python标准库concurrent.futures模块中的一个类,用于实现线程池。它提供了一种简单的方式来并发执行多个任务,从而提高程序的性能。
使用ThreadPoolExecutor可以通过以下步骤来创建和使用线程池:
1. 导入ThreadPoolExecutor类:
```python
from concurrent.futures import ThreadPoolExecutor
```
2. 创建ThreadPoolExecutor对象:
```python
executor = ThreadPoolExecutor(max_workers=5)
```
其中,max_workers参数指定了线程池中最大的线程数量。
3. 提交任务给线程池:
```python
future = executor.submit(function, *args, **kwargs)
```
其中,function是要执行的函数,*args和**kwargs是传递给函数的参数。submit方法会返回一个Future对象,可以用来获取函数的返回值或者判断任务是否完成。
4. 获取任务的返回值:
```python
result = future.result()
```
result方法会阻塞当前线程,直到任务完成并返回结果。
下面是一个使用ThreadPoolExecutor的简单示例:
```python
from concurrent.futures import ThreadPoolExecutor
import time
def task(name):
print(f"Task {name} started")
time.sleep(2)
print(f"Task {name} finished")
return f"Result from task {name}"
# 创建线程池
executor = ThreadPoolExecutor(max_workers=3)
# 提交任务给线程池
futures = []
for i in range(5):
future = executor.submit(task, i)
futures.append(future)
# 获取任务的返回值
for future in futures:
result = future.result()
print(result)
```
运行以上代码,会输出类似以下结果:
```
Task 0 started
Task 1 started
Task 2 started
Task 0 finished
Result from task 0
Task 3 started
Task 1 finished
Result from task 1
Task 4 started
Task 2 finished
Result from task 2
Task 3 finished
Result from task 3
Task 4 finished
Result from task 4
```
阅读全文