/************************************************************** File: div_conquer.cc Description: A program that implements a divide and conquer function computing the sum of an array. Author: Dana Vrajitoru Organization: IUSB, Computer and Information Sciences Date: September 2020 ***************************************************************/ #include #include #include #include using namespace std; #include "div_conquer.h" // global variables int size, limit=10, nr_thr; int counter = 0, global_id = 0, threads_done = 0, global_sum = 0; int *a = NULL, *result = NULL; pthread_mutex_t id_mutex, barrier_mutex, cout_mutex, data_mutex; pthread_cond_t allin_cond; // Creates the threads calling the Sum_thread function. void Create_threads(pthread_t *threads, int nr_threads) { for (int i=0; i> size; a = new int[size]; for (int i=0; i> nr_threads; nr_thr = nr_threads; result = new int[nr_threads]; } // A barrier function based on the number of threads implemented using // a conditional variable. It uses a global counter intialized as // 0. Each thread coming in increments the counter. If the count is // nrt equal to the number of threads, it goes into a wait on the // conditional variable. The thread that finds the counter equal to // the number of threads broadcasts the condition that releases all of // them. void Barrier(int nr_threads) { static int count = 0; pthread_mutex_lock(&barrier_mutex); count++; if (count == nr_threads) { pthread_cond_broadcast(&allin_cond); // last one in lets everyone go count = 0; } else pthread_cond_wait(&allin_cond, &barrier_mutex); pthread_mutex_unlock(&barrier_mutex); } // The thread function: gets an id number, commputes the partial sum on // its part of the array, then communicates the results globally using // one of the report functions. void * Sum_thread(void *arg) { int id, i, n, step, first, last, sum=0; Get_id(id); Global_to_local(n); step = n/nr_thr; first = id*step; if (id