python并发编程之线程池(三)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

在日常生活中,如果需要复用多线程去处理成千上万的任务时,我们不能无限的去新建线程,销毁线程,这样会导致服务器出现灾难性的后果,这时,我们就需要使用线程池,这样我们可以最程度的减少创建线程,销毁线程造成的资源消耗 下面我们来看一下python三种线程池的实现

一、concurrent.futures 中实现的ThreadPoolExecutor

示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。

from concurrent.futures import ThreadPoolExecutor
threadPool = ThreadPoolExecutor(max_workers=5, thread_name_prefix="thread")
for i in range(0, 10):
    future = threadPool.submit(foo, i,)
	print(future.result())

二、 multiprocessing.pool 中实现的ThreadPool

代码如下(示例):

In : from multiprocessing.pool import ThreadPool
In : pool = ThreadPool(5)
In : pool.map(lambda x: x**2, range(5))
Out: [0, 1, 4, 9, 16]

三、自定义一个线程池

代码如下(示例):

import threading
from queue import Queue

'''
线程池, 同时多个任务一起提交,提高并发度
'''


class WorkThread(threading.Thread):
    def __init__(self, queue):
        super().__init__()
        self._queue = queue
        self.daemon = True
        self.start()  # run()

    def run(self):
        while 1:
            fun, args, kwargs = self._queue.get()
            try:
                fun(*args, **kwargs)
            except Exception as e:
                raise e
            self._queue.task_done()


class ThreadPool(object):
    def __init__(self, size):
        self.size = size
        self.queue = Queue(size)
        for _ in range(size):
            WorkThread(self.queue)

    def add_task(self, f, *args, **kwargs):
        self.queue.put((f, args, kwargs))

    def join(self):
        self.queue.join()


# test
def foo(n):
    import time
    print('waiting 3s')
    time.sleep(3)
    print('waiting 5s')
    time.sleep(5)
    print(n ** 2)


pool = ThreadPool(5)
for i in range(10):
    pool.add_task(foo, i)
pool.join()

结果:
在这里插入图片描述


总结

利用好线程池,能使你程序事半功倍。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

crystalnsd

万水千山总是情,支持一下行不行

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值