0

So, I was curious how someone could get random values across multiple threads with the rand_r command. If I used time(NULL) for the seed everyone ends up with the sam seed because the threads are created so close together. There actions are all based on that random seed, so all the threads remain identical for the remainder of my program. How would one get [ USING RAND_R(*int seed) ] a random number that differed across all threads?

Thanks in advance.

guitar80
  • 716
  • 6
  • 19

2 Answers2

1

The man page for rand_r on Ubuntu Linux 14.04 suggests:

The value pointed to by the seedp argument of rand_r() provides only a very small amount of state, so this function will be a weak pseudo-random generator. Try drand48_r(3) instead.

TonyB
  • 927
  • 6
  • 13
  • 3
    How does this answer the question? Not to mention that's only true for Ubuntu, the man page may state something differently on another platform. –  Nov 03 '14 at 20:34
  • Thanks for the response. My assignment asks me to find a random number for my sleep times, but it insists I use rand_r... I saw this, but was trying to find an answer within the guidelines – guitar80 Nov 03 '14 at 20:46
  • The only suggestion I have to use a global variable for the seed variable, and only populate it at the start of the program, i.e. not prior to each `rand_r()` call. – TonyB Nov 03 '14 at 20:54
0

You could use arc4random to generate the seed values for each thread.

user3386109
  • 34,287
  • 7
  • 49
  • 68