AdamElKaroui
AdamElKaroui

Reputation: 81

Multiprocessing, return the function's value

def fun(a,b):
    return (a,b)

if __name__ == '__main__':
    jobs = []
    for i in range(10): # I want to use 10 CPUs

        p = multiprocessing.Process(target=fun,args=(a,b,))
        jobs.append(p)
        p.start()

Basically, I want to execute the function fun on 10 processors, so I get 10 results, but I want to store the returning values in two different arrays, so I get something like this in the end

x = [a,a,a,...,a]
y = [b,b,b,...,b]

Thanks

Upvotes: 0

Views: 1018

Answers (1)

Highstaker
Highstaker

Reputation: 1075

Probably a bad solution (because confusing and hard to read), but since your source is just two constants, it works. Except, it returns tuples, not lists:

import multiprocessing
import itertools

a=0.5
b=0.7
PROCS=10

def fun(a,b):
    return (a,b)

if __name__ == '__main__':
    with multiprocessing.Pool(processes=PROCS) as pool:
        result_a, result_b = zip(*pool.starmap(fun, zip(itertools.repeat(a,PROCS),itertools.repeat(b,PROCS))))

Upvotes: 1

Related Questions