how do I pass a variables value into the pthread create parameters using a void function?

46 Views Asked by At

I'm doing a monte Carlo simulation to calculate pi using threads, I believe the mass of my logic is correct. I just need to pass the correct value into the pthread create function under the C library i'm using, I just don't understand how fulfill the void function parameter that is required... any suggestions?

#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define Num_POINTS 10000
#define Num_Threads 4

unsigned int seed;


void *monte_carlo(void *t_ID);




long thread_points;
int total_hits;

pthread_mutex_t mutex;

void *monte_carlo(void *t_ID){

        float x,y;
        long k, hits;
        long my_id;
        my_id = (long)t_ID;


        seed = time(NULL) * (my_id + 1);

        hits = 0;
        for(k = 0; k < thread_points; k++){
                x = (float)rand_r(&seed)/(float)RAND_MAX * 2 - 1;
                y = (float)rand_r(&seed)/(float)RAND_MAX * 2 - 1;
                if (sqrt((x*x)+(y*y)) <=1){
                        hits = hits + 1;
                }
        }

        pthread_mutex_lock(&mutex);
        total_hits = total_hits + hits;
        pthread_mutex_unlock(&mutex);



}

void * test(void *total_hits) {
    printf("%d\n", total_hits);
    pthread_exit(NULL);
}
int main()
{
        struct timespec start, finish;
        double elapsed;

        clock_gettime(CLOCK_MONOTONIC, &start);

        pthread_t TID[Num_Threads]  ;
        float pi;
        srand(time(NULL));
        int i, j;
        int l;



        test(total_hits);
        for(i = 0; i < Num_Threads; i++){
        l = pthread_create(&TID[i], NULL, test, (void *)i);
        if (l){
        printf("ERROR");
        exit(-1);

      }

      }

      for(j=0;j<Num_Threads;j++){

      pthread_join(TID[i], NULL);
  }

    clock_gettime(CLOCK_MONOTONIC, &finish);

    elapsed = (finish.tv_sec - start.tv_sec);
    elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;

    printf( "Time: %lf\n", elapsed );


    pi = ((double)total_hits/(double)Num_POINTS)*4.0;          //p = 4(m/n)
    printf("Pi: %f\n", pi);
    return 0;
    pthread_exit(0);

}
0

There are 0 best solutions below