Clear Filters
Clear Filters

Parfor/spmd with random numbers

2 views (last 30 days)
JohnDapper on 2 Feb 2016
Commented: Brendan Hamm on 3 Feb 2016
In my code I want to run a function on each worker in parallel. The function is mexified C++ and (simply put) returns an image consisting of pixels with random intensity. Something like this:
parfor i = 1 : numiters
output(:,i) = myFn()
The trouble is that each output(:,i) is identical! Running the functions serially, like so:
for i = 1 : numiters
output(:,i) = myFn()
there are no troubles. Each output(:,i) is different. I thought that each worker is initialized with a random seed -- but I guess not. It seems that they are all initialized to the same seed. Any tips on how to overcome this issue?
Many thanks.
Edric Ellis
Edric Ellis on 3 Feb 2016
Walter is exactly right that MATLAB's built-in random number generation functions like rand and randn are seeded differently on each worker, and I would recommend using these functions to generate random numbers. If you're using a C function to generate the random numbers, you need to take account of how that function is being seeded. If, for example, it is seeded using the start time of the process, then you'll get the behaviour you observe.
Brendan Hamm
Brendan Hamm on 3 Feb 2016
Cleve Moler had a nice blog post a while back about Parallel Random Number Generators.

Sign in to comment.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!