아래 코드는 어떤 이유로 든 모든 프로세스에 대해 동일한 난수를 반환하는 난수 생성기를 생성합니다. 어떻게 그럴 수 있니? 뮤텍스에 문제가 있습니까?PRNG가 모든 프로세스에서 동일한 값을 반환합니다.
#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;
}
좋은 대답은 실제로 주요 문제인 것으로 보이는 것을 강조합니다. 질문자는 프로세스를 스레드와 혼동하고 있습니다. – Quantumboredom