Basically i need to make three threads B,C,D to work simultaneously. Thread B sums up the even indexes in a global array X , C sums up the odd indexes in X, D sums up both results while B and C are still summing. I used two mutexes to do so but its not working properly. In the array X given in the code below the results should be: evenSum = 47,oddSum = 127 ,bothSum = 174. any help is greatly appreciated! Thanks!!
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#define SIZE 20
int X[SIZE] = {5,4,5,3,7,9,3,3,1,2,9,0,3,43,3,56,7,3,4,4};
int evenSum = 0;
int oddSum = 0;
int bothSum = 0;
//Initialize two mutex semaphores
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void* sum_even_indexes(void* args){
int i;
for(i=0 ; i<20 ; i+=2){
pthread_mutex_lock(&mutex1);
evenSum+=X[i];
pthread_mutex_unlock(&mutex1);
}
pthread_exit(NULL);
}
void* sum_odd_indexes(void* args){
int i;
for(i=1 ; i<20 ; i+=2){
pthread_mutex_lock(&mutex2);
oddSum+=X[i];
pthread_mutex_unlock(&mutex2);
}
pthread_exit(NULL);
}
void* sum_of_both(void* args){
int i;
for(i=0 ; i<SIZE ; i++){
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
bothSum += (evenSum+oddSum);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
pthread_exit(NULL);
}
int main(int argc, char const *argv[]){
pthread_t B,C,D;
/***
* Create three threads:
* thread B : Sums up the even indexes in the array X
* thread C : Sums up the odd indexes in the array X
* thread D : Sums up both B and C results
*
* Note:
* All threads must work simultaneously
*/
pthread_create(&B,NULL,sum_even_indexes,NULL);
pthread_create(&C,NULL,sum_odd_indexes,NULL);
pthread_create(&D,NULL,sum_of_both,NULL);
//Wait for all threads to finish
pthread_join(B,NULL);
pthread_join(C,NULL);
pthread_join(D,NULL);
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
//Testing Print
printf("Odds Sum = %d\n",oddSum);
printf("Evens Sum = %d\n",evenSum);
printf("Both Sum = %d\n",bothSum);
return 0;
}