[英]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.我不明白为什么我必须使用
rand_r()
在线程 function 中生成随机数。 And also why I need to use different seed for each thread.还有为什么我需要为每个线程使用不同的种子。
why I need to use rand_r() in threads
为什么我需要在线程中使用 rand_r()
From the documentation of rand
: The function rand() is not reentrant or thread-safe, ... this can be done using the reentrant function rand_r().从
rand
的文档: function rand() 不是可重入的或线程安全的,...这可以使用可重入的 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. rand_r()
是一个伪随机数生成器。 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.
事实上,它是 100% 可预测的。 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.
要预测序列中的下一个数字,您只需要知道生成器的 state 及其使用的算法。
The seed for a pseudo-random generator provides a way to put the generator into a known, repeatable state.伪随机生成器的种子提供了一种将生成器放入已知的、可重复的 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.此外,如果您希望程序的不同运行获得不同的“随机”值,那么您必须在每次运行程序时使用不同的值作为种子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.