python中ThreadPoolExecutor线程池

ThreadPoolExecutor

python3标准库concurrent.futures中常用的线程池ThreadPoolExecutor特点:

  1. 主线程可以获取某一个线程的状态,以及返回值。
  2. 线程同步
  3. 让多线程和多进程的编码接口一致。
  4. 简单粗暴

上手操练

将使用ThreadPoolExecutor线程池,将文件读取出来,并在文件每一行行末追加内容_我是吊车尾

第一步,假设有个文件,20000行,第一行数据为”1“,后续自增。(直接代码写一个)

from concurrent.futures import ThreadPoolExecutor


index=1
line_list=[]
for i in range(20000):
   line_list.append(index)
   index += 1
with open("./test1.txt","a") as file:
   for line in line_list:
       file.write(str(line)+"\n")

第二步,将第一步中生成的文件读出来存储到list中,并用ThreadPoolExecutor多线程的在每一行的末尾追加内容“_我是吊车尾”

file_line_list = []
with open("./test1.txt", "r")as file:
    for line in file:
        file_line_list.append(line.strip('\n'))

def exec_function(opera_list):
    print("追加", opera_list + "_我是吊车尾")
    return opera_list + "_我是吊车尾"


from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor() as executor: # 使用with
    res = executor.map(exec_function, file_line_list, timeout=5)
print("追加完成!!!")

with open("./test2.txt", "w")as file:
    for line in res:
        file.write(line + "\n")

PS:建议使用with ThreadPoolExecutor(),如果使用for ThreadPoolExecutor(),在结束时,记得自己executor.shutdown,(with方法内部已经实现了wait(),在使用完毕之后可以自行关闭线程池,减少资源浪费。)

第三步,查看执行结果:

在这里插入图片描述在这里插入图片描述

贴下ThreadPoolExecutor类init方法代码

class ThreadPoolExecutor(_base.Executor):

    # Used to assign unique thread names when thread_name_prefix is not supplied.
    _counter = itertools.count().__next__

    def __init__(self, max_workers=None, thread_name_prefix=''):
        """Initializes a new ThreadPoolExecutor instance.

        Args:
            max_workers: The maximum number of threads that can be used to
                execute the given calls.
            thread_name_prefix: An optional name prefix to give our threads.
        """
        if max_workers is None:
            # Use this number because ThreadPoolExecutor is often
            # used to overlap I/O instead of CPU work.
            max_workers = (os.cpu_count() or 1) * 5
        if max_workers <= 0:
            raise ValueError("max_workers must be greater than 0")

        self._max_workers = max_workers
        self._work_queue = queue.Queue()
        self._threads = set()
        self._shutdown = False
        self._shutdown_lock = threading.Lock()
        self._thread_name_prefix = (thread_name_prefix or
                                    ("ThreadPoolExecutor-%d" % self._counter()))

其他

本文只涉及了最基本的应用,ThreadPoolExecutor中其实还有更多的参数可以使用,大家有兴趣可以继续深入。

corePoolSize:核心线程池的线程数量
maximumPoolSize:最大的线程池线程数量
keepAliveTime:线程活动保持时间,线程池的工作线程空闲后,保持存活的时间。
unit:线程活动保持时间的单位。
workQueue:指定任务队列所使用的阻塞队列

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
PythonThreadPoolExecutor线程池的一种实现方式,它提供了方便的接口来进行并发编程。在使用ThreadPoolExecutor时,通常会遇到异常捕获的问题。 当线程池的线程执行任务时,如果任务发生异常,异常会被捕获,并通过Future对象返回给调用者。我们可以通过检查Future对象的状态来获取异常信息。Future对象是一个表示异步计算结果的对象,它可以用来检查任务是否完成、取消任务、获取任务的结果等。 在ThreadPoolExecutor,可以通过submit方法来提交任务。这个方法返回一个Future对象,我们可以通过调用Future对象的result方法来等待任务完成并获取任务的结果。如果任务发生异常,result方法将会抛出异常,并将异常的类型和信息传递给调用者。 另外,我们还可以通过调用ThreadPoolExecutor的shutdown方法来关闭线程池。关闭线程池后,任何待处理的任务将会被取消,并且已提交但还未开始执行的任务将会被清除。我们可以通过调用Future对象的cancel方法来取消任务。 在代码,我们可以使用try-except语句块来捕获线程任务的异常。可以使用ThreadPoolExecutor的submit方法来提交任务,并通过返回的Future对象来获取任务的结果。在调用Future对象的result方法时,如果发生了异常,可以使用try-except语句块来捕获异常并处理异常。另外,在使用完线程池后,我们应该调用shutdown方法来关闭线程池,以释放资源。 总结起来,PythonThreadPoolExecutor提供了异常捕获机制,我们可以通过检查返回的Future对象来获取任务执行过程的异常信息。在使用完线程池后,我们应该及时关闭线程池,以释放资源。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值