3

I was working on two threads trying to generate random numbers seeding once seed(time(null)) in main(). Program got segmentation fault continuously until I figured out that when working with threads we must generate random numbers for all threads in their own routines and there was no seg fault then.

I tried to find answer on google as to why do we have to seed independently for all threads but did not find enough convincing answers. Could anyone please explain? Thanks!!

Vbp
  • 1,912
  • 1
  • 22
  • 30
  • 3
    http://stackoverflow.com/questions/6161322/using-rand-with-multiple-threads-in-c should answer your question – Dariusz Mar 14 '13 at 13:46
  • Please show us your segfaulting code (the more concise the better). – NPE Mar 14 '13 at 13:46

3 Answers3

5

To give you a short and straight answer:

rand() is not thread safe.

It should not be called from multiple threads without explicit critical section.

Dariusz
  • 21,561
  • 9
  • 74
  • 114
3

As mentioned by Dariusz, the problem is that rand() is not thread safe.

However, you can use nrand48 (http://linux.about.com/library/cmd/blcmdl3_nrand48.htm) which takes as argument the storage used for the seed.

In this way, you can associate to each thread a different seed storage, such that invocation to the random number generators will operate on distinct memory area.

emanuele
  • 31
  • 2
0

If this is not for cryptography but for Monte-Carlo situations or something in that vein instead, the Mersenne Twister is a good solution. In particular, this version http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/DC/dc.html Has been adjusted specifically for parallel or threaded usage. The work was done by the original authors, and the PRNG has a very long period.

Randy Howard
  • 2,165
  • 16
  • 26