Answer:
A mutex is used here.
A mutex is a locking mechanism set before using a shared resource and is released after using the shared resource. When the lock is set, only one task accesses the mutex.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
#include<unistd.h>
pthread_t tid[2];
int flag=0;
int a = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *thread_a(void *arg)
{
pthread_mutex_lock(&lock);
a += 2;
pthread_mutex_unlock(&lock);
flag = 1;
return NULL;
}
void *thread_b(void *arg)
{
int b = 0;
if(flag){
b++;
}
b += 3;
pthread_mutex_lock(&lock);
a -= b;
pthread_mutex_unlock(&lock);
return NULL;
}
int main()
{
while(1) {
pthread_create(&tid[0],NULL,thread_a,NULL);
pthread_create(&tid[1],NULL,thread_b,NULL);
sleep(1);
}
pthread_exit(NULL);
return 0;
}