Use of mutex locks and conditional variables in Linux multithreading
------------------------
# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>
# Include <pthread. h>
Pthread_mutex_t count_lock;
Pthread_cond_t count_nonzero;
Unsigned count;
Void * decrement_count (void * Arg)
{
Pthread_mutex_lock (& count_lock );
While (COUNT = 0)
Pthread_cond_wait (& count_nonzero, & count_lock );
Count = count-1;
Printf ("line: % d/N", _ line __, count );
Pthread_mutex_unlock (& count_lock );
Pthread_exit (null );
}
Void * increment_count (void * Arg)
{
Pthread_mutex_lock (& count_lock );
If (COUNT = 0)
Pthread_cond_signal (& count_nonzero );
Count = count + 1;
Printf ("line: % d/N", _ line __, count );
Sleep (2 );
Pthread_mutex_unlock (& count_lock );
Pthread_exit (null );
}
Int main ()
{
Pthread_t id1;
Pthread_mutex_init (& count_lock, null );
Pthread_cond_init (& count_nonzero, null );
Pthread_create (& id1, null, decrement_count, null );
Increment_count (null );
Pthread_join (id1, null );
Return 0;
}