I tested out two very simple examples of printing even/odd numbers in multithreaded code, one using pthread_cond_t and the other not.
void *even(void *arg)
{
while(count < MAX)
{
pthread_mutex_lock(&mutex);
if(count % 2 == 0)
printf("%d ", count++);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *odd(void *arg)
{
while(count < MAX)
{
pthread_mutex_lock(&mutex);
if(count % 2 == 1)
printf("%d ", count++);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *even(void *arg)
{
while(count < MAX) {
pthread_mutex_lock(&mutex);
while(count % 2 != 0) {
pthread_cond_wait(&cond, &mutex);
}
printf("%d ", count++);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
pthread_exit(0);
}
void *odd(void *arg)
{
while(count < MAX) {
pthread_mutex_lock(&mutex);
while(count % 2 != 1) {
pthread_cond_wait(&cond, &mutex);
}
printf("%d ", count++);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
pthread_exit(0);
}
The above two codes behave differently. 1st code output:
0 1 2 3 4 5 6 7 8 9 10
0 1 2 3 4 5 6 7 8 9 10
0 1 2 3 4 5 6 7 8 9 10
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 10
0 1 2 3 4 5 6 7 8 9 10
0 1 2 3 4 5 6 7 8 9
2nd code output:
0 1 2 3 4 5 6 7 8 9 10
0 1 2 3 4 5 6 7 8 9 10
0 1 2 3 4 5 6 7 8 9 10
0 1 2 3 4 5 6 7 8 9 10
The reason for the inconsistent output for 1st code could be that:
in between the following calls in even thread: suppose count == 8
pthread_mutex_unlock(&mutex);
..... --> here, the odd thread increments the count by one before this thread could check the the following while condition
while(count < MAX)
so 10 is missed occasionally.
But for the code using pthread_cond_wait(), there is no such inconsistency, although, the same argument can be made for it aswell: in between these calls in even thread:suppose count == 8
pthread_cond_signal(&cond);// mutex is already unlocked before condition is signaled.
.... --> here, the odd thread can increment the count to 10 before the even thread could check the while condition
while(count < MAX)
But in practice,this never happend for 2nd code, so somehow, pthread_cond_wait() code takes care of such inconsistency, but it seems unclear to me how?
Is there anything else going on behind the scenes in pthread_cond_wait() that helps out?
Thanks