mardi 25 mai 2021

How to generate different random values at each subprocess during a multiprocessing?

I need to generate a different random value at each sub-process but I realized that this local variable is rewritten or shared between each sub-process. See the example below to understand the problem I am facing:

import numpy as np
from multiprocessing import Pool

def func(i):
    i2 = i**2
    random_variable = np.round(np.random.normal(), 3)
    return i2, random_variable

if __name__ == '__main__':
    with Pool() as pool:
        result = pool.map(func, [1, 2, 3, 4, 5])
        print(result)

output:

[(1, -0.122), (4, -0.122), (9, -0.122), (16, -0.122), (25, -0.122)]

What could be the reason of this output? And how can I generate a different random variable at each sub-process?




Aucun commentaire:

Enregistrer un commentaire