hi I\'m having problems getting my c program to run. It is suppose to calculate
ID: 3543482 • Letter: H
Question
hi I'm having problems getting my c program to run. It is suppose to calculate pi using pthreads. You should be able to enter a number and then a thread will count the points entered and store the result in a global variable. When the thread exits the parent thread will calculate and output the result of pi. This is my code
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <string.h>
#define SEED 35791246
void *pifunction(void *pts);
#define NUMBER_OF_THREADS 1
//#define NUMBER_OF_COUNTS
/* global variable */
double result = 0;
int main (int argc, const char * argv[]) {
int number_of_pts = 0;
int i;
printf("Enter the number of random points: ");
scanf("%d", number_of_pts);
pthread_t pts_create[NUMBER_OF_THREADS];
for (i = 0; i < NUMBER_OF_THREADS; i++)
pthread_create(&pts_create[i], 0, pifunction, &number_of_pts);
for (i = 0; i < NUMBER_OF_THREADS; i++)
pthread_join(pts_create[i],NULL);
printf("The estimation of pi is: ",result);
return 0;
}
void *pifunction(void *pts)
{
int points;
points = *((int *)pts);
double x;
double y;
double z;
int i;
/* initialize random numbers */
srand(SEED);
int count=0;
for (i=0; i<points; i++)
{
x = (double)rand()/RAND_MAX;
y = (double)rand()/RAND_MAX;
z = x*x+y*y;
if (z<=1) count++;
}
result=(double)count/points*4;
pthread_exit(0);
}
Explanation / Answer
check my ans at
http://codepad.org/fQ2UAXPL
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.