python打造线程池

复制代码
复制代码
# coding=utf-8
import  threading
import Queue
import time
import traceback

class ThreadPoolExecutor(object):
    def __init__(self, max_works):
        self._q = Queue.Queue()                
        self.max_works=max_works
        self.started=0

    def worker(self):
        while True:
            (fn, args) = self._q.get()
            try:
                fn(*args)
            except Exception, e:
                print '线程池执行错误,item是:',item, '错误原因是:',e,traceback.format_exc()
            finally:
                pass
                self._q.task_done()

    def submit(self, fn, *args):
        item = (fn,args)
        self._q.put(item)
        self.start_work()


    def start_work(self):
        if self.started==0:
            for i in range(self.max_works):
                t=threading.Thread(target=self.worker)
                t.setDaemon(True)                     ###利用daemon的特性:父线程退出时子线程就自动退出。
                t.start()
            self.started=1

    def wait_all_finish(self):
        self._q.join()
复制代码

 

测试

复制代码
#coding=utf8
import threading
from xccfb import ThreadPoolExecutor
import time

if __name__=="__main__":
    tlock=threading.Lock()
    def fun(strx):
        with tlock:
            print time.strftime('%H:%M:%S'),strx
        time.sleep(2)

    threadPoolExecutor=ThreadPoolExecutor(3)
    for i in range(10):
        threadPoolExecutor.submit(fun, 'hello')
    threadPoolExecutor.submit(fun, 'hi')
    threadPoolExecutor.wait_all_finish()     ###注释掉就可以先print over
    print time.strftime('%H:%M:%S'), 'over'
复制代码

 

 

复制代码

 

使用wait_all_finish()的queue.join()方法阻塞主线程,当队列中有任务还要执行时候不往下执行。不想阻塞就不要写这句。

posted @   北风之神0509  阅读(210)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示