c - PRNG 在所有进程中返回相同的值

标签 c random posix mutex process

下面的代码(并且可以按原样编译)导致随机数生成器出于某种原因为所有进程返回完全相同的随机数。怎么可能呢?我对互斥体做错了吗?

#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define RETURN_FAILURE_IF_TRUE(condition, ...) \
{ \
    if(condition) \
    { \
        fprintf(stderr, __VA_ARGS__); \
        return EXIT_FAILURE; \
    } \
}

#define RETURN_FAILURE_IF_FALSE(condition, ...) \
    RETURN_FAILURE_IF_TRUE(!(condition), __VA_ARGS__)

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int nextRandomDouble(double* d)
{
    if(pthread_mutex_lock(&mutex) != 0) return 0;
    *d = drand48();
    if(pthread_mutex_unlock(&mutex) != 0) return 0;
    return 1;
}

int main()
{
    const int processes = 5;
    srand48(time(NULL));

    for(int i = 0; i < processes; ++i)
    {
        pid_t pid = fork();
        RETURN_FAILURE_IF_TRUE(pid < 0, "Fork failed.\n");
        if(pid == 0)
        {
            double d;
            RETURN_FAILURE_IF_FALSE(nextRandomDouble(&d), "PRNG failed.\n");
            printf("rnd: %f\n", d);
            return EXIT_SUCCESS;
        }
    }

    for(int i = 0; i < processes; ++i)
    {
        int status;
        pid_t pid = waitpid(-1, &status, 0);
        RETURN_FAILURE_IF_TRUE(
            (pid != 1) && (status != 0), "Child exit failed.\n"
        );
    }
    return EXIT_SUCCESS;
}

最佳答案

srand48(time(NULL));

您在每个进程中为 PRNG 播种从进程开始到秒的时间。这意味着在同一个第二个开始的所有进程都为具有相同值的 PRNG 播种。

尝试:

srand48((getpid()*2654435761U)^time(NULL));

关于c - PRNG 在所有进程中返回相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8056371/

相关文章:

c - Swift:将未初始化的 C 结构传递给导入的 C 函数

c - 尝试使用 mingw 构建和编译 lua 5.3.3 , undefined reference 错误

c - 仅在 while 循环结束时打印文本

Javascript - 无需循环即可生成多个随机数

c++ - 如何从 C++ vector 中获取 2 个随机(不同)元素

c - 如何跟踪所有要清理的后代进程?

c - 特征向量(谱)分解

c++11 - 在不使用 iostream 的情况下保存 c++11 随机生成器的状态

linux - 屏蔽信号是否丢失或放入队列?

multithreading - 可选的取消点