Bam19
Bam19

Reputation: 1

Monte Carlo with threading

This is what I am trying to accomplish.Write a multithreaded program in C (or C++/C#) that creates 5 threads. Each thread should generate 1,000 random points and count the number of points that occur within the circle. The main thread should wait for the five threads to terminate one after another. Once a thread is terminated, the main thread updates the value of PI using the total number of points in the circle and the total number of points generated by the terminated thread. For example, the main thread waits for the first thread to terminate. When the first thread is terminated, the main thread incorporates the total number of points in the circle obtained by the first thread to update the value of PI. Next, the main thread waits for the second thread to terminate. When the second thread is terminated, the main thread updates the value of PI using the total number of points in the circle obtained by the second thread, and so on.

I keep getting an error saying that non-void function doesn't return a value, so is there anyway I can get around that or what are some alternatives for me?

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

long incircle = 0;
long ppt; /* points per thread*/
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *runner() {
    long incircle_thread = 0;
    
    unsigned int rand_state = rand();
    long i;
    for (i = 0; i < ppt; i++) {
        double x = rand_r(&rand_state) / ((double)RAND_MAX + 1) * 2.0 - 1.0;
        double y = rand_r(&rand_state) / ((double)RAND_MAX + 1) * 2.0 - 1.0;
        if (x * x + y * y < 1) {
            incircle_thread++;
        }
    }
    pthread_mutex_lock(&mutex);
    incircle += incircle_thread;
    pthread_mutex_unlock(&mutex);
}

int main(int argc, const char *argv[])
{
    if (argc != 3) {
        fprintf(stderr, "usage: ./pi <total points> <threads>\n");
        exit(1);
    }
    long totalpoints = atol(argv[1]);
    int thread_count = atoi(argv[2]);
    ppt = totalpoints / thread_count;

    time_t start = time(NULL);
    srand((unsigned)time(NULL));
    pthread_t *threads = malloc(thread_count * sizeof(pthread_t));
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    int i;
    for (i = 0; i < thread_count; i++) {
        pthread_create(&threads[i], &attr, runner, (void *) NULL);
    }
    for (i = 0; i < thread_count; i++) {
        pthread_join(threads[i], NULL);
    }
    pthread_mutex_destroy(&mutex);
    free(threads);
    double points_per_thread = 0.0;
    printf("Pi: %f\n", (4. * (double)incircle) / ((double)points_per_thread * thread_count));
    printf("Time: %d sec\n", (unsigned int)(time(NULL) - start));
    return 0;
}
'''

Upvotes: 0

Views: 710

Answers (1)

sode
sode

Reputation: 256

The return type of 'runner' is void*, so that's what it needs to return

In your case, it looks like you would just want to add

return NULL;

Upvotes: 1

Related Questions