并发编程--进程池与线程池-练习3
通过继承multipocessing类,实现一个进程池。
代码如下:
# coding = utf-8 ''' 实现一个进程池 ''' import time import multiprocessing from multiprocessing import Manager, Queue class MyProcess(object): def __init__(self, num): super().__init__() # self.queue = Manager().Queue() self.queue = multiprocessing.JoinableQueue() for i in range(1, num+1): multiprocessing.Process(target=self.work, daemon=True).start() def work(self): ''' 从队列获取任务并执行 :return: ''' while True: try: func, args, kwargs = self.queue.get() func(*args, **kwargs) except Exception as e: print(e) finally: self.queue.task_done() def apply_async(self, func, args=(), kwargs={}): ''' 接收任务,并将其存入到队列中 :param func: :param args: :param kwargs: :return: ''' self.queue.put((func, args, kwargs)) def join(self): ''' 控制进程结束 :return: ''' self.queue.join() def func1(): print('111') time.sleep(2) def func2(): print('222') time.sleep(2) def func3(): print('333') if __name__ == '__main__': process = MyProcess(2) process.apply_async(func1) process.apply_async(func2) process.apply_async(func3) process.join() print('任务结束!')