- #1
James889
- 192
- 1
Hi,
I've recently started C and i have a quick question
in the code below i increase the variable Balance in two threads, but somehow the final Balance is still equal to the initial value. Why?
I've recently started C and i have a quick question
in the code below i increase the variable Balance in two threads, but somehow the final Balance is still equal to the initial value. Why?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int Balance = 100;
void *ThreadRoutine1(void) {
pthread_mutex_lock(&mutex);
Balance++;
pthread_mutex_unlock(&mutex);
printf("Balance is now:%d\n",Balance);
pthread_exit(NULL);
}
void *ThreadRoutine2(void) {
pthread_mutex_lock(&mutex);
Balance++;
pthread_mutex_unlock(&mutex);
printf("Balance is now:%d\n",Balance);
pthread_exit(NULL);
}
int main() {
pthread_t thread1,thread2;
int thread1_id;
int thread2_id; thread1_id = pthread_create(&thread1,NULL,(void *)ThreadRoutine1,NULL);
thread2_id = pthread_create(&thread2,NULL,(void *)ThreadRoutine2,NULL);
pthread_join(&thread1,NULL);
pthread_join(&thread2,NULL);
printf("Final Balance is:%d\t",Balance);
}