Python线程池的基本使用
1. 线程池的基本概念
线程池是一种管理线程的工具,它创建了一组线程,这些线程可以被用来执行任务。线程池中的线程可以被重复利用,从而避免了频繁创建和销毁线程的开销。在Python中,concurrent.futures模块提供了一个简单的线程池实现ThreadPoolExecutor。
2. 创建和使用线程池
from concurrent.futures import ThreadPoolExecutor
# 创建线程池
threadPool = ThreadPoolExecutor(max_workers=3)
对任务简单封装一下
class Task:
def __init__(self, name, target, *args):
self.name = name
self.target = target
self.args = args
def __call__(self):
print(f"{
self.name}任务开始")
result = self.target(*self.args)
print(f"{
self.name}任务完成")
return result
使用Task类,我们可以将任务的名称、执行函数以及参数封装起来,然后提交到线程池中:
# 提交任务到线程池
for i in

最低0.47元/天 解锁文章
356

被折叠的 条评论
为什么被折叠?



