Skip to content
Snippets Groups Projects
Commit 9b1b8a88 authored by Lucas Christesen Ahler's avatar Lucas Christesen Ahler
Browse files

Multiprocessing exercise

parent 09296a02
No related branches found
No related tags found
No related merge requests found
CFLAGS = -Wall -O1 -std=gnu11 #-DNDEBUG
CFLAGS += -pthread
LDLIBS = -lm
default: main
./$< > out.txt
.PHONEY: clean
clean:
$(RM) main
\ No newline at end of file
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<math.h>
#ifndef NDEBUG
#define TRACE(args...) fprintf(stderr,args)
#else
#define TRACE(...)
#endif
typedef struct {int points;int* successes;unsigned int* seed;} params;
void* bar(void* arg) {
params* p = (params*)arg;
for(int i=0;i<(*p).points;i++) {
double x = (double)rand_r((*p).seed)/RAND_MAX;
double y = (double)rand_r((*p).seed)/RAND_MAX;
double dist = sqrt(pow(x,2)+pow(y,2));
if(dist<=1) {
*((*p).successes)=*((*p).successes)+1;
}
}
return NULL;
}
int main() {
int points = (int)5e8;
int suc1=0,suc2=0,suc3=0,suc4=0;
unsigned int seed1=0,seed2=100,seed3=1000,seed4=2000;
params p1 = {points, &suc1, &seed1};
params p2 = {points, &suc2, &seed2};
params p3 = {points, &suc3, &seed3};
params p4 = {points, &suc4, &seed4};
pthread_t thread1, thread2, thread3;
pthread_attr_t* attributes = NULL;
pthread_create(&thread1, attributes, bar, (void*)&p1);
pthread_create(&thread2, attributes, bar, (void*)&p2);
pthread_create(&thread3, attributes, bar, (void*)&p3);
bar((void*)&p4);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
pthread_join(thread3,NULL);
double pi = (((double)*p1.successes+(double)*p2.successes+(double)*p3.successes+(double)*p4.successes)/(4*points))*4;
printf("Estimate of Pi: %g\n",pi);
return 0;
}
\ No newline at end of file
Estimate of Pi: 3.14159
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment