[英]Using Python's Multiprocessing Module To Generate Class Attributes
我是多处理模块的新手,我想知道一个类是否有可能产生它可以与之通信的工作者类。 我有一个实例,其中一个对象接收数据,并且需要根据该数据快速构造属性,这些属性本身就是对象。 以下代码是一个简单的情况:
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类使用该输出为其自身分配属性。
弄清楚了。 将Master类的实例化包含在if __name__ == '__main__'
解决此问题。 显然这是Windows问题。 此处的更多信息:
https://docs.python.org/2/library/multiprocessing.html#multiprocessing-programming
这看起来像是multiprocessing.Pool的完美用例。 您可能会注意到您的程序挂起,并且Master
没有收到您期望的任何属性。 那是因为它当时还没有收到任何信息,因为它需要在out_queue
上进行out_queue
才能从队列中读取信息,因为在您的程序要从out_queue
读取时,它为空。
一个简单的解决方法是在队列的get
方法上阻止并等待超时,如下所示:
while True:
attr = out_queue.get(True, 0.1)
if not attr:
break
self.attributes.append(attr)
这将起作用,但这不是一个干净的解决方案。 您可以对其进行修改,并进行实验以获得所需的期望结果,我建议使用前哨值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.