python 中有实现进程池,但是没有线程池。所以下面实现一个线程池。
from queue import LifoQueue,PriorityQueue,Queue
from threading import Thread
import time
class ThreadPoolManger():
"""线程池管理器"""
def __init__(self, thread_num):
# 初始化参数
self.work_queue = Queue()
self.thread_num = thread_num
self.__init_threading_pool(self.thread_num)
def __init_threading_pool(self, thread_num):
self.ts=[]
# 初始化线程池,创建指定数量的线程池
for i in range(thread_num):
thread = ThreadManger(self.work_queue)
thread.start()
self.ts.append(thread)
def add_job(self, func, *args):
# 将任务放入队列,等待线程池阻塞读取,参数是被执行的函数和函数的参数
self.work_queue.put((func, args))
def join(self):
for t in self.ts:
t.join()
class ThreadManger(Thread):
"""定义线程类,继承threading.Thread"""
def __init__(self, work_queue):
Thread.__init__(self)
self.work_queue = work_queue
self.daemon = True
def run(self):
# 启动线程
while True:
target, args = self.work_queue.get()
if target=="stop":
break
target(*args)
self.work_queue.task_done()
import random
queue=LifoQueue()
global A
A=False
def aa(i):
print("A",i)
queue.put(i)
time.sleep(random.uniform(0,1))
def a():
global A
thread_pool = ThreadPoolManger(3)
for i in range(16):
thread_pool.add_job(aa,*(i,))
thread_pool.add_job("stop",*(0,))
thread_pool.add_job("stop",*(0,))
thread_pool.add_job("stop",*(0,))
thread_pool.join()
A=True
def b():
global A
while True:
if queue.empty() and A:
break
a=queue.get()
print(a)
time.sleep(0.5)
ts=[]
time.sleep(1)
ts.append(Thread(target=a))
ts[-1].start()
time.sleep(1)
ts.append(Thread(target=b))
ts[-1].start()
for t in ts:
t.join()