I wrote a simple program using pthread but my results are random....
#define NTHREADS 2
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
void *add(void* numbers){
pthread_mutex_lock( &mutex1 );
int *n = (int*) numbers;
float sum;
for(int i = 0; i < 5; i++){
sum = sum + n[i] +5;
}
cout << sum/5<<endl;
pthread_mutex_unlock( &mutex1 );
}
void *substract(void* numbers){
pthread_mutex_lock( &mutex1 );
int *n = (int*) numbers;
float sum;
for(int i = 0; i < 5; i++){
sum = sum + n[i] -10;
}
cout << sum/5<<endl;
pthread_mutex_unlock( &mutex1 );
}
main(){
pthread_t thread_id[NTHREADS];
int i, j;
int *numbers = new int[5];
numbers[0] = 34; numbers[1] = 2; numbers[2]= 77; numbers[3] = 40; numbers[4] = 12;
pthread_create( &thread_id[0], NULL, add, (void*) numbers);
pthread_create( &thread_id[1], NULL, substract, (void*) numbers );
pthread_join( thread_id[0], NULL);
pthread_join( thread_id[1], NULL);
exit(EXIT_SUCCESS);
}
The output of the program is random....Sometimes it got
-2.42477e+26
23
Sometimes it got only one strange number such as
235.69118e+13
(empty space)
I have also tried only to use one thread, but the result is still random. For example, I only used thread to calculate "add", the result is sometimes 38, which is correct, but sometimes is a very strange number.
Where I did wrong? Thank you .
NTHREADS=1or with all the thread code removed?subtractattempts to unlock the mutex twice instead of locking it then unlocking it.