Python简单实现线程池

2018-03-15  本文已影响0人  东方灵将
class ToDoList:
    def __init__(self, maxSize):
        self.maxSize = maxSize #最大线程数
        self.tasks = Queue() #任务队列
        self.workList = dict() #工作列表
        self.lock = threading.Lock() #线程锁

    def start(self, target=None, args=None):
        if target is not None:
            self.tasks.put((target, args))
        self.lock.acquire()
        if len(self.workList) < self.maxSize:
            if not self.tasks.empty():
                task_id = str(uuid.uuid1())
                func, paras = self.tasks.get()
                task = self._create_task(func, task_id)
                task = threading.Thread(target=task, args=paras)
                task.start()
                self.workList[task_id] = task
        self.lock.release()

    def _create_task(self, target, taskId):
        # 任务装饰器
        def wrapper(*args,**kwargs):
            try:
                result = target(*args,**kwargs)
                return result
            finally:
                del self.workList[taskId]
                # 任务结束后重新从队列里取下个任务执行
                self.start()

        return wrapper
上一篇 下一篇

猜你喜欢

热点阅读