저는 다중 처리 모듈을 처음 사용하기 때문에 클래스가 통신 할 수있는 작업자 클래스를 생성 할 수 있는지 궁금합니다. 나는 객체가 데이터를받는 인스턴스를 가지고 있으며 객체 자체 인 데이터를 기반으로 속성을 빠르게 생성해야한다. 다음 코드는 단순한 경우입니다.Python의 다중 처리 모듈을 사용하여 클래스 속성 생성
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 클래스는 해당 출력을 사용하여 자체 특성을 지정합니다.
Sean, 답장을 보내 주셔서 감사합니다. 그것은 매우 흥미 롭습니다. in_queue.join()에 매달려 있다고 생각했습니다. 즉 작업자가 작업을 수행하지 못하고있었습니다. 그러나 in_queue.join()을 전달하는 경우 모든 작업이 완료되고 out_queue가 결과로 가득해야한다는 의미가 아닙니까? 나는 또한 모든 근로자들이 합류했는지 확인하고 위와 동일한 문제를 겪는 지 실험했다. – Adam
Sean, 솔루션을 구현했는데 제대로 작동하지 않는 것 같습니다. 구현이 있습니까? – Adam
나는 그것을한다. 그러나 그것은 나의 개인의 휴대용 개인 컴퓨터 위에있다. 내가 일하러 나갈 때 나는 그것을 게시하려고 노력할 것이다. – sean