pthreads - C: Producer / Consumer -
one of task @ school fix code. producer , consumer thread should alternatly increment local variable , print out, have no idea how fix it.
it should possible producer , consumer thread can indefinitely, if start executable stops arbitrarily.
it great if explain me behavior.
here code:
#include <sys/types.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> static pthread_mutex_t mutex; static pthread_cond_t cond_consumed = pthread_cond_initializer; static pthread_cond_t cond_produced = pthread_cond_initializer; static void *producer( void *arg ) { unsigned long count=0; while( 1 ) { printf("producer: wait...\n"); pthread_mutex_lock( &mutex ); // enter critical section pthread_cond_wait( &cond_consumed, &mutex ); printf("producer: produce %ld...\n", count++); pthread_cond_signal( &cond_produced ); pthread_mutex_unlock( &mutex ); // leave critical section } return null; } static void *consumer( void *arg ) { unsigned long count=0; sleep( 1 ); pthread_cond_signal( &cond_consumed ); while( 1 ) { printf("consumer: wait...\n"); pthread_mutex_lock( &mutex ); pthread_cond_wait( &cond_produced, &mutex ); printf("consumer: consume %ld...\n", count++); pthread_cond_signal( &cond_consumed ); pthread_mutex_unlock( &mutex ); } return null; } int main( int argc, char **argv, char **envp ) { pthread_t p1, p2; if (pthread_mutex_init( &mutex, null )) { perror("pthread_mutex_init"); return -1; } pthread_create( &p2, null, consumer, null ); pthread_create( &p1, null, producer, null ); pthread_join( p1, null ); pthread_join( p2, null ); pthread_mutex_destroy( &mutex ); return 0; }
the output should example:
$ ./event producer: wait... consumer: wait... producer: produce 0... producer: wait... consumer: consume 0... consumer: wait... producer: produce 1... producer: wait... consumer: consume 1... consumer: wait... producer: produce 2... producer: wait... consumer: consume 2... consumer: wait... ....
the problem can occur thread_a signals before thread_b has reached pthread_cond_wait
statement. thread_b never see signal , instead keep waiting it.
according specs:
the pthread_cond_signal() , pthread_cond_broadcast() functions have no effect if there no threads blocked on cond.
this result in deadlock, experiencing.