gpt4 book ai didi

c - 如何使用 rand_r() 在 C 中创建线程安全的随机数生成器?

转载 作者:行者123 更新时间:2023-12-03 12:48:19 59 4
gpt4 key购买 nike

我被要求不要使用 rand(),因为它们不是“线程安全的”,并且每次也使用不同的种子值。我在 GitHub 上找到了使用如下种子值的示例:

unsigned int seed = time(NULL);

这只有几秒钟的精度。由于程序在 1 秒内运行,我最终得到每个实例相同的随机数。

我将如何修复此算法,使其仅使用 rand_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;
}

最佳答案

rand_r 函数接受一个指向状态变量的指针。这在第一次调用 rand_r 之前设置为种子值。然后每次调用 rand_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;
}

关于c - 如何使用 rand_r() 在 C 中创建线程安全的随机数生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43151361/

59 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com