Issue
Consider the following contrived examples-
Say I have a thread that modifies a global variable:
void thread_1(void* param) {
for (int i=0; i<10; i++) {
x += i; // x is global.
}
}
And say I have another thread that modifies the same global variable:
void thread_2(void* param) {
while (1) {
x = 0; // x is global.
usleep(20000);
}
}
How do I pause the second thread's execution to wait until the first thread is finished executing to continue execution in the second thread safely to prevent a race condition from occurring?
Solution
If you want to create threads for example 6 threads you dont need to use 6 functions for that like you did , void thread1 and thread2.you must create them like :
pthread_mutex_t lock= PTHREAD_MUTEX_INITIALIZER; // this locks the critical arrea
pthread_cond_t consum = PTHREAD_COND_INITIALIZER; // and this is a conditional variable
pthread_t consumerN[2];
//then in your main function
int main(){
pthread_create(&consumerN[1],NULL,thread_1,NULL);// go to thread_1
pthread_create(&consumerN[2],NULL,thread_2,NULL);//go to thread_2
}
void thread_1(int *param){
pthread_mutex_lock(&lock);
pthread_cond_wait(&consum,lock);
for (int i=0; i<10; i++) {
x += i; // x is global.
}
pthread_mutex_unlock(&lock);
}
void thread_2(int *param){
pthread_mutex_lock(&lock);
pthread_cond_wait(&consum,lock);
while(1){
x=0;
sleep(2000);
}
pthread_mutex_unlock(&lock);
}
Answered By - gregni