Im coding an aplication that runs the Monaco algorithm using different thread numbers, them being 2,4,6 and 8 to calculate the value of PI. The objective is too see a speed increase when using more threads. The problem is, my code is not dividing the work, but simply doing the work 2 times!
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <math.h>
#include <string.h>
#define SEED 35791246
void *monaco(int arcg, char* argv) {
clock_t t1, t2;
float pi;
t1 = clock();
t2 = clock();
float diff = ((float)(t2 - t1) / 1000000.0F );
printf("\n");
printf("Thread number = %d\n", (int)(pthread_self()));
printf("Total Time: %f segundos\n", diff);
printf("\n");
printf("\n");
return 0;
}
void run_test(int num_thread) {
pthread_t pth_arr[num_thread];
int i = 0;
for (i = 0; i < num_thread; i++) {
pthread_create(&pth_arr[i], NULL, monaco, NULL);
}
for (i = 0; i < num_thread; i++) {
pthread_join(pth_arr[i], NULL);
}
}
int main(count) {
int num_thread = 9;
int pontos=20000;
double x,y;
count=0;
double z;
float pi;
int j = 0;
int i = 0;
srand(SEED);
count = 0;
for (i = 1; i < num_thread; i++) {
if (i==1)
{
continue;
}
if (i==3)
{
continue;
}
if (i==5)
{
continue;
}
if (i==7)
{
continue;
}
for (j = 0; j<pontos; j++) {
x = (double)rand()/RAND_MAX;
y = (double)rand()/RAND_MAX;
z = x*x+y*y;
if (z<=1) count++;
}
pi=(double)count/pontos * 4;
printf ("Points used are: %d , and the Pi estimate is: %g \n", pontos,pi);
printf ("Using %d threads.\n", i);
run_test(i);
}
return 0;
}
The output I get is:
Points used are: 20000 , and the Pi estimate is: 3.1288
Using 2 threads.
Thread number = -1332082944
Total Time: 0.000002 segundos
Thread number = -1340475648
Total Time: 0.000002 segundos
Thread number = -1340475648
Total Time: 0.000002 segundos
Points used are: 20000, and the Pi estimate is: 6.2932
Using 4 threads.
Thread number = -1332082944
Total time: 0.000002 segundos
Thread number = -1348868352
Total time: 0.000001 segundos
Thread number = -1357261056
Total time: 0.000001 segundos
Thread number = -1340475648
Total time: 0.000002 segundos
Points used are: 20000 , and the Pi estimate is: 9.4232
How can I make it divide the work instead of doing it 2 times?