/***************************************************************** File: integral.cc Description: Computes the integral of a function in parallel with pthreads. Author: Dana Vrajitoru Organization: IUSB Date: August, 2020 ******************************************************************/ #include #include #include using namespace std; #include "integral.h" // global variables float a, b, integral = 0; // boundaries int nr_threads, nr_intervals; // Creates the threads calling the compute_integral function, and to // each of them it passes the value of i converted to a pointer to // serve as id number. void create_threads(pthread_t *threads, int nr_threads) { for (long i = 0; i < nr_threads; i++) if (pthread_create(&threads[i], NULL, compute_integral, (void *)i) != 0) cout << "pthread_create fails" << endl; } // Joins all of the threads so that the program doesn't end before // they have finished the work. void synchronise(pthread_t *threads, int nr_threads) { for (int i = 0; i < nr_threads; i++) if (pthread_join(threads[i], NULL) != 0) cout << "pthread_join fails" << endl; } // Inputs the boundaries of the interval, the number of threads, and // the total number of divisions. It returns the number of threads. int input_data() { cout << "Enter the number of threads" << endl; cin >> nr_threads; cout << "Enter the boundaries of the interval" << endl; cin >> a >> b; cout << "Enter the overall number of divisions" << endl; cin >> nr_intervals; return nr_threads; } // The function computing the integral. To be used to create threads void *compute_integral(void *arg) { long id = long(arg); cout << "Thread " << id << " running" << endl; float sum = 0, x; float start, length, deltax; int divisions = nr_intervals / nr_threads; // number of divisions // for this thread length = (b - a) / nr_threads; // interval length for this thread start = a + id * length; // where this threads starts from deltax = length / divisions; // computation incremment for (int i=0; i < divisions; i++) // computing the integral sum += deltax * F(start + i * deltax); integral += sum; // add it to the global integral return NULL; } // A function we can compute the integral for // integral from 1 to x of 1/t dt = ln(x) float F(float x) { if (x != 0) return 1/x; else return 0; } // Output the computed integral void output_results() { cout << "The integral is equal to " << integral << endl; }