Beispiel für Parallelisierung von Jobs mit Ergebnis welche als Liste zurückgegeben werden.
#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
import os
from multiprocessing import Pool
def worker(job):
x, y = job
result = x ** y
return os.getpid(), result
if __name__ == '__main__':
jobs = [(1, 2), (3, 4), (5, 6), (11, 12), (13, 14), (15, 16), (21, 22), (23, 24), (25, 26)]
result_buffer = []
pool = Pool(processes=5)
for job in jobs:
result_buffer.append(pool.apply_async(worker, args=(job,)))
pool.close()
pool.join()
results = [r.get() for r in result_buffer]
print results
for pid, result in results:
print "working pid was: %s" % pid
print "result is: %s" % result
print "---"Beispiel Ergebnis:
$python mp_with_result.py [(7992, 1), (7992, 81), (7992, 15625), (7992, 3138428376721L), (7992, 3937376385699289L), (7992, 6568408355712890625L), (7992, 122694327386105632949003612841L), (7992, 480250763996501976790165756943041L), (7992, 2220446049250313080847263336181640625L)] working pid was: 7992 result is: 1 --- working pid was: 7992 result is: 81 --- working pid was: 7992 result is: 15625 --- working pid was: 7992 result is: 3138428376721 --- working pid was: 7992 result is: 3937376385699289 --- working pid was: 7992 result is: 6568408355712890625 --- working pid was: 7992 result is: 122694327386105632949003612841 --- working pid was: 7992 result is: 480250763996501976790165756943041 --- working pid was: 7992 result is: 2220446049250313080847263336181640625 ---
