This code calculates the sum of all integers in an array, evenly dividing the work between multiple threads. However every once in a while the thread numbers as well as the localsum of the thread are messed up. I am assuming it's because void* param and globalindex are accessed by multiple threads at the same time. What does not make sense is the fact that it happens, even though I mutexlocked every global variable in this code. How do I fix this?
#include<string>
#include<iostream>
#include<fstream>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
using namespace std;
int y =0;
int sum=0;
int array[1000000];
int x=0;
int leftoverHandle = 0;
int globalindex = 0;
int eachThreadHandles =0;
void* add(void* param){
pthread_mutex_lock(&mutex);
int localindexup = globalindex + eachThreadHandles;
int localindexdown = globalindex;
int localsum=0;
long localparam = (long)param;
if(y != leftoverHandle ){
localindexup++;
y++;
}
pthread_mutex_unlock(&mutex);
while(localindexdown<localindexup){
pthread_mutex_lock(&mutex);
sum = sum+array[localindexdown];
localsum = localsum+array[localindexdown];
localindexdown++;
pthread_mutex_unlock(&mutex);
}
pthread_mutex_lock(&mutex);
globalindex = localindexdown;
printf("Thread %ld", localparam);
printf(": %d\n", localsum);
pthread_mutex_unlock(&mutex);
}
int main(int argc, char ** argv){
if(argc != 3){
cout<<"Incorrect number of argument";
exit(1);
}
string line;
string f = argv[1];
const char *filename = f.c_str();
int maxthreads = atoi(argv[2]);
FILE* inFile = fopen(filename,"r");
int i=0;
if(inFile == NULL){
cout<<"fopen failed"<<endl;
}
fscanf(inFile, "%d",&i);
while(!feof(inFile)){
array[x]=i;
x +=1;
fscanf(inFile,"%d",&i);
}
fclose(inFile);
pthread_t id[maxthreads];
leftoverHandle = x%maxthreads;
eachThreadHandles = (x - leftoverHandle)/maxthreads;
for(long i=0; i< maxthreads;i++){
long status = pthread_create(&id[i], NULL, add, (void*) i);
if(status){
printf("Error creating thread! \n");
exit(0);
}
}
for(long i=0; i<maxthreads;i++){
pthread_join(id[i], NULL);
}
cout<<"Sum="<<sum<<endl;
return 0;
}