-
-
Save igor-shevchenko/7248163 to your computer and use it in GitHub Desktop.
Distributed Monte Carlo estimation of pi using posix message queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/types.h> | |
#include <unistd.h> | |
#include <sys/wait.h> | |
#include <math.h> | |
#include <mqueue.h> | |
#include <sys/stat.h> | |
#include <errno.h> | |
#define RADIUS 1000 | |
#define QNAME "/piqueue" | |
int is_in_circle(double x, double y, double radius) { | |
return x * x + y * y < radius * radius; | |
} | |
double test_pi (int iters){ | |
int in_circle = 0; | |
double x, y; | |
for (int i = 0; i < iters; ++i){ | |
x = (rand() % (2 * RADIUS)) - RADIUS, | |
y = (rand() % (2 * RADIUS)) - RADIUS; | |
if (is_in_circle(x, y, RADIUS)){ | |
in_circle++; | |
} | |
} | |
return 4 * (in_circle / (double) iters); | |
} | |
int main(int argc, char** argv){ | |
if (argc < 2){ | |
printf("expected args: proc, iters\n"); | |
exit(1); | |
} | |
int proc = atoi(argv[1]), | |
iters = atoi(argv[2]); | |
struct mq_attr attr; | |
mqd_t msgq_id; | |
attr.mq_maxmsg = 300; | |
attr.mq_msgsize = sizeof(double); | |
msgq_id = mq_open(QNAME, O_RDWR | O_CREAT, 644, &attr); | |
mq_unlink(QNAME); | |
for (int i = 0; i < proc; ++i){ | |
if (!fork()){ | |
srand(time(0) * getpid()); | |
double pi = test_pi(iters); | |
mq_send(msgq_id, &pi, sizeof(double), 1); | |
exit(0); | |
} | |
} | |
int status, prio; | |
double sum = 0.0, result; | |
for (int i = 0; i < proc; ++i){ | |
wait(&status); | |
mq_receive(msgq_id, &result, sizeof(double), &prio); | |
sum += result; | |
} | |
printf("%f\n", sum / proc); | |
exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment