#include #include #include #include void *fproducer(void *); void *fconsumer(void *); typedef struct { pthread_mutex_t working; int hasData; int buffer; } UserData; int main(int argc, char *argv[]) { pthread_t producer, consumer; int rp, rc; UserData ud; pthread_mutex_init( &(ud.working), NULL ); ud.hasData = 0; ud.buffer = 0; // spawn the producer thread rp = pthread_create( &producer, NULL, fproducer, &ud ); // spawn the consumer thread rc = pthread_create( &consumer, NULL, fconsumer, &ud); // wait until both are done (join) pthread_join( producer, NULL ); pthread_join( consumer, NULL ); pthread_mutex_destroy( &(ud.working) ); // terminate printf("Terminating\n"); return(0); } void *fproducer( void *userdata ) { int i; UserData *ud = (UserData *)userdata; for(i=0;i<10;) { if( !ud->hasData) { printf("producer locking thread\n"); pthread_mutex_lock( &(ud->working) ); printf("Producer placing %d\n", i+1); ud->buffer = i+1; ud->hasData = 1; i++; printf("producer unlocking thread\n"); pthread_mutex_unlock( &(ud->working) ); } } return( NULL ); } void *fconsumer( void *userdata ) { int i; UserData *ud = (UserData *)userdata; for(i=0;i<10;) { if(ud->hasData) { printf("consumer locking thread\n"); pthread_mutex_lock( &(ud->working) ); printf("Consumer received data %d\n", ud->buffer); ud->hasData = 0; i++; printf("consumer unlocking thread\n"); pthread_mutex_unlock( &(ud->working) ); } } return( NULL ); }