首先是工作线程类
import threading
class TaskThread(threading.Thread):
def __init__(self):
super(TaskThread,self).__init__()
self.e = threading.Event()
self.setDaemon(True)
def run(self):
while True:
try:
self.task.doAction()
except Exception,e:
print e
finally:
self.e.clear()
self.e.wait()
def addTask(self,task):
self.task = task
然后是线程池类
import threading
from Queue import Queue
from TaskThread import TaskThread
class ThreadPool(object):
__instance = None
__lock = threading.Lock()
def __init__():
pass
def __call__(self):
self.run()
@classmethod
def getInstance(self):
self.__lock.acquire()
if not self.__instance:
self.__instance = super(ThreadPool,self).__new__(self)
self.__lock.release()
return self.__instance
def initPool(self,pool_max_size = 10,task_queue_size = 100):
self.pool = []
self.tasks = Queue(task_queue_size)
for i in range(pool_max_size):
self.pool.append(TaskThread())
def run(self):
while True:
th = None
for t in self.pool:
if not t.e.isSet():
th = t
break
if th is not None:
try:
task = self.tasks.get(0)
except:
pass
else:
th.addTask(task)
th.e.set()
if not th.isAlive():
th.start()
def addTask(self,task,timeout = 0):
try:
self.tasks.put(task,timeout)
return True
except:
return False
粗略的测试了下,没有发现什么问题,只是目前有几个问题比较纠结:
1、要不要把ThreadPool类写成单例,因为照现在写法,继承threading.Thread之后不能start,只能依靠另外起一条线程来执行run方法
2、工作线程类执行绑定方法的时候是直接调用约定方法还是用__call__
3、总觉得目前的设计怪怪的,想继续拆分几个类出来,但又有过度设计之嫌
明天开始研究gui了,初步选定wxPython,哈哈,理我完成"神器"的目标又进一步了...