The below code (and which is compilable as is) results in the random number generator returning the very same random number for all processes for some reason. How could that be? Am I doing something wrong with the mutex?
#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;
}