0

I can't understand why I have to use rand_r() in generating random numbers in a thread function. And also why I need to use different seed for each thread.

Dylan Nico
  • 39
  • 8
  • Does this answer your question? [Using stdlib's rand() from multiple threads](https://stackoverflow.com/questions/6161322/using-stdlibs-rand-from-multiple-threads) – Hitokiri May 13 '20 at 14:09

2 Answers2

0

why I need to use rand_r() in threads

From the documentation of rand : The function rand() is not reentrant or thread-safe, ... this can be done using the reentrant function rand_r().

why I need different seed for each threads?

you don't necessary need, it is your choice to use or not the same seed in all the threads

bruno
  • 32,421
  • 7
  • 25
  • 37
0

Why I need different seed in each?

rand_r() is a pseudo-random number generator. That is to say, it generates a pseduo-random sequence of numbers: Each call returns the next number in the sequence.

"Random" means "unpredictable." If you have a generator for a truly random sequence of numbers, you will be unable to predict the next number in the sequence, no matter how many of the preceding numbers you already know.

A "Pseudo random" is like a random sequence in some ways—can be used as if it was random in some applications—but it isn't random at all. In fact, it is 100% predictable. All you need to know to predict the next number in the sequence is to know the state of the generator and the algorithm that it uses.

The seed for a pseudo-random generator provides a way to put the generator into a known, repeatable state. If you provide the same seed to two different instances of the generator, then both generators will return exactly the same sequence of values.


Do you want each thread to get exactly the same sequence as every other thread? It's up to you. If that's what you want, then seed each one with the same value. If you want them to get different "random" numbers, then seed each generator with a different value.

Also, if you want different runs of the program to get different "random" values, then you have to seed with a different value each time the program is run.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57
  • P.S., If you're looking for a way to get different seed values each time you run the program, and if your program is intended to run under Linux, then you might want to read about the [`getrandom()` system call](http://man7.org/linux/man-pages/man2/getrandom.2.html). – Solomon Slow May 13 '20 at 15:12