서브 클래스 multiprocessing.Process
:이 방법으로
내가 값을 다시 얻을 수 없다 그러나, 어떻게 사용할 수있는 큐?
프로세스 ... 내 컴퓨터에
from multiprocessing import Process, Queue
class Processor(Process):
def __init__(self, queue, idx, **kwargs):
super(Processor, self).__init__()
self.queue = queue
self.idx = idx
self.kwargs = kwargs
def run(self):
"""Build some CPU-intensive tasks to run via multiprocessing here."""
hash(self.kwargs) # Shameless usage of CPU for no gain...
## Return some information back through multiprocessing.Queue
## NOTE: self.name is an attribute of multiprocessing.Process
self.queue.put("Process idx={0} is called '{1}'".format(self.idx, self.name))
if __name__ == "__main__":
NUMBER_OF_PROCESSES = 5
## Create a list to hold running Processor object instances...
processes = list()
q = Queue() # Build a single queue to send to all process objects...
for i in range(0, NUMBER_OF_PROCESSES):
p=Processor(queue=q, idx=i)
p.start()
processes.append(p)
# Incorporating ideas from this answer, below...
# https://stackoverflow.com/a/42137966/667301
[proc.join() for proc in processes]
while not q.empty():
print "RESULT: {0}".format(q.get()) # get results from the queue...
는,이 결과 ...
multiprocessing.Process
은 다음 서브 클래 싱하는 방법의 예를 결과를받을
Queue()
을 필요로
$ python test.py
RESULT: Process idx=0 is called 'Processor-1'
RESULT: Process idx=4 is called 'Processor-5'
RESULT: Process idx=3 is called 'Processor-4'
RESULT: Process idx=1 is called 'Processor-2'
RESULT: Process idx=2 is called 'Processor-3'
$
multiprocessing.Pool
:
FWIW, multiprocessing.Process
의 서브 클래 싱을 발견 한 단점은 multiprocessing.Pool
의 기본 제공되는 모든 장점을 활용할 수 없다는 것입니다. Pool
은 매우 좋은 API를 제공합니다. 생산자 및 소비자 코드가 대기열을 통해 서로 통신해야합니다.
다음과 같은 예에서, 내가 pool_job()
에서 입력 및 출력 값을 캡슐화하는 dict()
를 사용 ... 그냥 창조적 반환 값을 많이 할 수 있습니다 ...
from multiprocessing import Pool
def pool_job(input_val=0):
# FYI, multiprocessing.Pool can't guarantee that it keeps inputs ordered correctly
# dict format is {input: output}...
return {'pool_job(input_val={0})'.format(input_val): int(input_val)*12}
pool = Pool(5) # Use 5 multiprocessing processes to handle jobs...
results = pool.map(pool_job, xrange(0, 12)) # map xrange(0, 12) into pool_job()
print results
이 결과 :
[
{'pool_job(input_val=0)': 0},
{'pool_job(input_val=1)': 12},
{'pool_job(input_val=2)': 24},
{'pool_job(input_val=3)': 36},
{'pool_job(input_val=4)': 48},
{'pool_job(input_val=5)': 60},
{'pool_job(input_val=6)': 72},
{'pool_job(input_val=7)': 84},
{'pool_job(input_val=8)': 96},
{'pool_job(input_val=9)': 108},
{'pool_job(input_val=10)': 120},
{'pool_job(input_val=11)': 132}
]
분명히 오류 처리와 같이 pool_job()
에는 많은 개선 사항이 있지만 분명히 필수적입니다. FYI this answer은 multiprocessing.Pool
을 사용하는 방법에 대한 또 다른 예를 제공합니다.
을 그래서,에 메서드 중 하나가 매개 변수 오른쪽으로 Queue 객체를 받아 들여야합니까? –
완료! 큐를 수락하는 init 메서드를 만들었습니다. 이 차례로 멀티 프로세싱을 확장합니다. 직접 큐를 수락하는 프로세스 : –
정정 주셔서 감사. 이 코드'return self.queue.put (self.return_name())'은 큐를 반환합니까? –