【发布时间】:2014-10-21 19:05:21
【问题描述】:
我是多处理模块的新手,想知道一个类是否有可能产生可以与之通信的工作类。我有一个对象接收数据的实例,并且需要根据该数据快速构造属性,这些属性本身就是对象。下面的代码是一个简单的例子:
class Worker(multiprocessing.Process):
def __init__(self, in_queue, out_queue):
multiprocessing.Process.__init__(self)
self.in_queue = in_queue
self.out_queue = out_queue
def run(self):
#Loop through the in_queue until a None is found
for tup in iter(self.in_queue.get,None):
#Try to manipulate the data
try:
self.out_queue.put(tup[0]*tup[1])
except:
self.out_queue.put('Error')
self.in_queue.task_done()
#Remove the None from the in_queue
self.in_queue.task_done()
class Master():
def __init__(self,data):
#Initialize some data to be operated on
self.data=data
def gen_attributes(self):
#Initialize Queues to interact with the workers
in_queue=multiprocessing.JoinableQueue()
out_queue=multiprocessing.Queue()
#Create workers to operate on the data
for i in range(4):
Worker(in_queue,out_queue).start()
#Add data to the input queue
for tup in self.data:
in_queue.put(tup)
#Stop Condition for each worker
for _ in range(4):
in_queue.put(None)
in_queue.close()
#Wait for processes to finish
in_queue.join()
#Store the output as new attributes of the class
self.attributes=[]
for _ in range(0,out_queue.qsize()):
self.attributes.append(out_queue.get())
#Create and instance of the Master class, and have it generate it's own attributes using the multiprocessing module
data=[(1,2),(2,2),(3,4)]
M=Master(data)
M.gen_attributes()
print M.attributes
本质上,Master 类的实例是使用给定数据生成的。然后,主类将该数据传递给多个工作人员进行操作并放入输出队列中。 Master 类然后使用该输出来分配自己的属性。
【问题讨论】: