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

时间:2017-04-01 00:13:41

标签: c multithreading random

我被要求不使用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;
}

1 个答案:

答案 0 :(得分:1)

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;
}
相关问题