What you need to do is to seed the random number generator once for each process in the multiprocessing pool (rather than for each call to rand
) and the way to do that is with a pool initializer, i.e. specifying the initializer argument on the multiprocessing.Pool
constructor. This function you specify will be called once for each process in the pool before any tasks are executed and can be used to perform any one-time initialization such as setting global variables or, in this case, seeding the random number generator for this process.
import numpy as np
from numpy.random import randn, seed
def init_pool_processes():
seed()
def testfun(X):
y = randn()
return y
# Required by Windows:
if __name__ == '__main__':
from multiprocessing import Pool
pool = Pool(processes=8, initializer=init_pool_processes)
result = pool.map(testfun, np.arange(8))
print(result)
Prints:
[-0.01738709180801345, -0.6941424935875462, 0.41955492420787543, -0.890711442154167, -0.6894630549510319, 1.1549486347982545, -0.27329303494286733, 0.16447656347746123]