Untitled

mail@pastecode.io avatarunknown
plain_text
12 days ago
2.6 kB
2
Indexable
Never
#include <pthread.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

/* this data is shared by the thread(s) */
int threads;
unsigned long long iterations;
double *pi;
int current_calc = 0;

void *runner(void *param); /* the thread */

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        fprintf(stderr, "usage: a.out <iterations> <threads>\n");
        /*exit(1);*/
        return -1;
    }
    if (atoi(argv[1]) < 0 || atoi(argv[2]) < 0)
    {
        fprintf(stderr, "Arguments must be non-negative\n ");
        /*exit(1);*/
        return -1;
    }

    /* populate variables... */
    // Extracting the values from the commmand line.
    iterations = atoi(argv[1]);
    threads = atoi(argv[2]);
    // Separate space in memory for the PI array.
    pi = malloc(threads * sizeof(double));
    /* create the thread identifiers */
    // this variable is to point to the first element of the threads array.
    pthread_t *tid;
    // We make an array that contains threads and its of size threads
    tid = (pthread_t *)malloc(threads * sizeof(pthread_t));
    /* create set of attributes for the thread */
    pthread_attr_t attr;
    /* get the default attributes */
    // Use this function to initialize the threads attibutes to the default.
    pthread_attr_init(&attr);
    /* create threads */
    // pi = 4 [ 1 - 1/3 + 1/5 - 1/7 + 1/9 ... +((-1)^n)/(2n+1) ]
    for (int i = 0; i < threads; i++)
    {
        pthread_create(&tid[i], &attr, runner, NULL);
    }
    /* now wait for the threads to exit */
    for (int i = 0; i < threads; i++)
    {
        pthread_join(tid[i], NULL);
    }
    /* compute and print results */
    double total = 0;
    for (int num = 0; num < threads; num++)
    {
        total += pi[num] * 4.0;
    }

    printf("pi = %.15f\n", total);
    return 0;
}
/**
 * The thread will begin control in this function
 */
void *runner(void *param)
{
    // returns the ID of the current thread
    int threadid = pthread_self(); // in the range of: [1, n]
    // printf("Thread: %d currently working");

    // Complete function
    // Each thread will execute for #iterations/#thread times
    // Increase n by #threads times.
    int thread_part = current_calc++;
    for (int n = thread_part * (iterations / threads) + 1; n <= (thread_part + 1) * (iterations / threads); n++)
    {
        // Summing all the terms for that thread's cycles.
        // It doesn't matter in what order we sum the terms.
        // pi = 4 [ 1 - 1/3 + 1/5 - 1/7 + 1/9 ... +((-1)^n)/(2n+1) ]
        pi[thread_part] += pow(-1.0, n) / ((2.0 * n) + 1.0);
    }

    pthread_exit(0);
}