2

I have a program in which I generate a lot of random numbers, and my program is very parallelizable. However, when I run it in parallel, it breaks. The source of the problem is related to the random number generation, which can be shown by running the code below (this is actually a lot slower to run in parallel than not, but it quickly demonstrates my problem). If you run this once, it appears to work fine. However, if you re-run the array creation part in F# interactive WITHOUT "let rnd = System.Random()", you get an array of zeroes. However, if it is not in parallel, you can re-run it as many times as you want with no problem.

let rnd = System.Random()
let arr=Array.Parallel.init 10000000 (fun s -> rnd.NextDouble()) 

There is probably something simple about parallel random number generation of which I am unaware.

rytido
  • 472
  • 3
  • 15

1 Answers1

3

In the documentation for the Random class it says that instance members are not guaranteed to be thread safe.

I found a blog entry that has some options for using Random in a thread-safe manner. http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx

toad
  • 1,351
  • 8
  • 14