长期潜伏在这里。
我有一个线程控制器对象。此对象接受其他名为"Checks"的对象。这些检查会拉入与其条件匹配的数据库行。线程管理器轮询每个检查(询问它的DB行,也就是工作单元),然后将每一行与对该检查对象的引用一起排队。我们的想法是,N个线程将进入并从队列中提取一个项目,并执行相应的Check的do_work方法。do_work方法将返回Pass\Fail,所有通行证都将排队等待进一步处理。
主脚本(未显示)实例化检查,并使用add_check将其添加到线程管理器中,然后调用kick_off_work。
到目前为止,我正在测试,它只是锁定了:
import Queue
from threading import Thread
class ThreadMan:
def __init__(self, reporter):
print "Initializing thread manager..."
self.workQueue = Queue.Queue()
self.resultQueue = Queue.Queue()
self.checks = []
def add_check(self, check):
self.checks.append(check)
def kick_off_work(self):
for check in self.checks:
for work_unit in check.populate_work():
#work unit is a DB row
self.workQueue.put({"object" : check, "work" : work_unit})
threads = Thread(target=self.execute_work_unit)
threads = Thread(target=self.execute_work_unit)
threads.start()
self.workQueue.join();
def execute_work_unit(self):
unit = self.workQueue.get()
check_object = unit['object'] #Check object
work_row = unit['work'] # DB ROW
check_object.do_work(work_row)
self.workQueue.task_done();
print "Done with work!!"
输出很简单:
Initializing thread manager...
In check1's do_work method... Doing work
Done with work!!
(locked up)
我想运行整个队列
您应该只在execute_work_unit中添加一个"while",否则它会在第一次迭代时停止:
def execute_work_unit(self):
while True:
unit = self.workQueue.get()
check_object = unit['object'] #Check object
work_row = unit['work'] # DB ROW
check_object.do_work(work_row)
self.workQueue.task_done();
print "Done with work!!"
看看那里:http://docs.python.org/2/library/queue.html#module-队列
编辑:要完成它,只需在中的self.workQueue.join()之后添加threads.joindef kick_off_work(self):