Thread example using arrays

Another Approach

pi-mtfn.c:

#include <stdio.h>   /* printf                  */
#include <stdlib.h>  /* exit, atoi              */
#include <pthread.h> /* thread create/join/exit */

double circle_pi(int rectangles);  /* Find PI using a quarter circle */
double leibniz_pi(int iterations); /* Find PI using a series         */
double atan_pi(int rectangles);    /* Find PI using a curve          */

#define NUM_THREADS 3
typedef  double (*PI_FUNCTION)(int);

/* Thread data */
struct pi_data
{
  int iterations;    /* Number of iterations/rectangles */
  PI_FUNCTION pi_fn; /* The pi function to call         */
  double result;     /* The value of pi returned        */
};

void *thread_fn(void *p)
{
  struct pi_data *data = (struct pi_data *)p;
  data->result = data->pi_fn(data->iterations);
  return NULL; /* Result is passed back via structure */
}

int main(int argc, char **argv) 
{
  int iterations = 1000 * 1000 * 100; 
  int i;
  
    /* Data is in arrays now */
  pthread_t threads[NUM_THREADS];
  struct pi_data data[NUM_THREADS];
  
    /* Add functions here, if you have more functions */
  PI_FUNCTION pi_functions[] = {circle_pi, leibniz_pi, atan_pi};

  if (argc > 1)
    iterations = 1000 * 1000 * atoi(argv[1]);

    /* Create threads with data passing */
  for (i = 0; i < NUM_THREADS; i++)
  {
    data[i].iterations = iterations;
    data[i].pi_fn = pi_functions[i];
    pthread_create(&threads[i], NULL, thread_fn, &data[i]);
  }
  
    /* Wait on the threads */
  for (i = 0; i < NUM_THREADS; i++)
    pthread_join(threads[i], NULL);
  
    /* Add a printf statements for more pi functions */
  printf("Iterations: %10i\n", iterations);
  printf(" circle:%20.16f\n", data[0].result);
  printf("leibniz:%20.16f\n", data[1].result);
  printf("   atan:%20.16f\n", data[2].result);
 
  return 0;
}
Output:
Iterations:  200000000
 circle:  3.1415926568498080
leibniz:  3.1415926485894077
   atan:  3.1415926536631549

real    0m2.422s
user    0m6.484s
sys     0m0.000s