参照c++的线程池,使用python的threading库实现线程池。
import threading
import time
# 线程池的任务,包含一个可调用对象和一个参数数组
class ThreadTask(object):
def __init__(self, job, args=list()):
self.task = job
self.args = args
# 线程池对象
class ThreadPool(object):
# 初始化线程池的线程、任务队列、任务队列读写锁、睡眠唤醒线程的condition对象,并开启所有线程
def __init__(self, thread_length):
self.task_list = list()
self.task_lock = threading.RLock()
self.task_condition = threading.Condition()
self.thread_length = thread_length
self.thread_list = list()
for i in range(0 , thread_length):
self.thread_list.append(threading.Thread(name='Thread '+str(i), target=ThreadPool.thread_work,
args=[self]))
for<