python 线程池的用法
时间: 2023-12-05 12:40:15 浏览: 31
以下是Python中使用线程池的两种方式及其使用方法:
1. 使用第三方库threadpool
```python
import threadpool
# 定义线程池中的函数
def func(arg1, arg2):
# do something
pass
# 创建线程池
pool = threadpool.ThreadPool(10)
# 创建任务列表
args_list = [(1, 2), (3, 4), (5, 6)]
# 创建任务
tasks = threadpool.makeRequests(func, args_list)
# 将任务加入线程池
for task in tasks:
pool.putRequest(task)
# 等待所有任务完成
pool.wait()
```
2. 使用Python3中的concurrent.futures.ThreadPoolExecutor库
```python
from concurrent.futures import ThreadPoolExecutor
# 定义线程池中的函数
def func(arg1, arg2):
# do something
pass
# 创建线程池
with ThreadPoolExecutor(max_workers=10) as executor:
# 创建任务列表
args_list = [(1, 2), (3, 4), (5, 6)]
# 提交任务
results = [executor.submit(func, *args) for args in args_list]
# 获取结果
for future in results:
result = future.result()
# do something with result
```