简体   繁体   中英

why I need to use rand_r() in threads and why I need different seed for each threads?

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM