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

btr*_*tty 2 c random multithreading

我被要求不要使用,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;
}
Run Code Online (Sandbox Code Playgroud)

dbu*_*ush 8

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;
}
Run Code Online (Sandbox Code Playgroud)