我的印象是python通过引用传递对象,所以从逻辑上讲(我认为),将字典传递给线程的工作函数将允许我设置新的键值对,这些键值对将在工作函数返回后保留。不幸的是,我好像错了!
事不宜迟,下面是一个测试用例:
from Queue import Queue
from threading import Thread
def work_fn(dictionary, dfield):
dictionary[dfield] = True
class Worker(Thread):
"""Thread executing tasks from a given tasks queue"""
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kargs = self.tasks.get()
try:
func(*args, **kargs)
except Exception, e:
print e
self.tasks.task_done()
class ThreadPool(object):
"""Pool of threads consuming tasks from a queue"""
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for i in range(num_threads):
Worker(self.tasks)
def add_task(self, func, *args, **kargs):
"""Add a task to the queue"""
self.tasks.put((func, args, kargs))
def wait_completion(self):
"""Wait for completion of all the tasks in the queue"""
self.tasks.join()
if __name__ == '__main__':
pool = ThreadPool(4)
data = [{} for _ in range(10)]
for i, d in enumerate(data):
pool.add_task(work_fn, d, str(i))
pool.wait_completion()
for d in data:
print d.keys()
这里到底发生了什么?
我应该采取什么不同的做法?
在打印结果之前,我看不出您在哪里等待任务完成。似乎您需要在生成作业后的后续循环中收集结果。