如何使用rand_r()在C中创建线程安全的随机数生成器?
我被要求不要使用如何使用rand_r()在C中创建线程安全的随机数生成器?,c,multithreading,random,C,Multithreading,Random,我被要求不要使用rand(),因为它们不是“线程安全的”,并且每次都使用不同的种子值。我在GitHub上找到了使用如下种子值的示例: unsigned int seed=time(NULL) 它的精度只有秒。由于程序运行时间不到1秒,因此每个实例都会得到相同的随机数 我该如何修复此算法,使其仅使用rand\u r()或任何其他“线程安全”方法来生成10个随机数 int main() { for(int i = 0; i < 10; i++){ int random;
rand()
,因为它们不是“线程安全的”,并且每次都使用不同的种子值。我在GitHub上找到了使用如下种子值的示例:
unsigned int seed=time(NULL)代码>
它的精度只有秒。由于程序运行时间不到1秒,因此每个实例都会得到相同的随机数
我该如何修复此算法,使其仅使用rand\u r()
或任何其他“线程安全”方法来生成10个随机数
int main()
{
for(int i = 0; i < 10; i++){
int random;
unsigned int seed = time(NULL);
random = 1 + (rand_r(&seed)% 10);
printf("%d\n",random);
}
return 0;
}
intmain()
{
对于(int i=0;i<10;i++){
int随机;
无符号整数种子=时间(NULL);
随机数=1+(随机数(&seed)%10);
printf(“%d\n”,随机);
}
返回0;
}
函数采用指向状态变量的指针。这在第一次调用rand\r
之前设置为种子值。然后每次调用rand\u r
,都会传入该值的地址
为了线程安全,每个线程都需要有自己的状态变量。但是,您不希望对每个线程的状态变量使用相同的初始值,否则每个线程将生成相同的伪随机值序列
您需要使用每个线程不同的数据(如线程id)以及其他信息(如时间和/或pid)为状态变量设定种子
例如:
// 2 threads, 1 state variable each
unsigned int state[2];
void *mythread(void *p_mystate)
{
unsigned int *mystate = p_mystate;
// XOR multiple values together to get a semi-unique seed
*mystate = time(NULL) ^ getpid() ^ pthread_self();
...
int rand1 = rand_r(mystate);
...
int rand2 = rand_r(mystate);
...
return NULL;
}
int main()
{
pthread_t t1, t2;
// give each thread the address of its state variable
pthread_create(&t1, NULL, mythread, &state[0]);
pthread_create(&t2, NULL, mythread, &state[1]);
...
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
和这么多类似的问题一样-只有一次种子。嗯……奇怪。为什么多次播种会导致数字完全相同?因为rand\u r
是一个具有单个参数的确定性函数,即seed
的值。