#include #include /* about Stock methods */ int max=30; int stock=0; int get(){ return stock; } void set(int x){stock=x;} int inc(){ set(get()+1); return get(); } int dec(){ set(get()-1); return get(); } int full(){ return get()>=max;} int empty(){ return get()<=0;} pthread_mutex_t stockm; pthread_cond_t stockc; void buy(){ pthread_mutex_lock( &stockm ); while(empty()){ pthread_cond_wait(&stockc, &stockm); } dec(); pthread_cond_broadcast(&stockc); pthread_mutex_unlock( &stockm ); } void supply(){ pthread_mutex_lock( &stockm ); while(full()){ pthread_cond_wait(&stockc, &stockm); } inc(); pthread_cond_broadcast(&stockc); pthread_mutex_unlock( &stockm ); } /* Customer */ int buycount=0; void* customer(void* x){ while(1){ buy(); buycount++; usleep(random()%1000); } } /* Customer2 */ int buycount2=0; void* customer2(void* x){ while(1){ buy(); buycount2++; usleep(random()%1020); } } /* Supplyer */ int supplycount=0; void* producer(void* x){ while(1){ supply(); supplycount++; usleep(random()%1010); } } void* ui(void* x){ while(1){ printf("buy=%d supply=%d stock=%d\n", buycount, supplycount, get()); } } main(){ pthread_t thre1, thre2, thre3, thre4; pthread_setconcurrency( 4 ); pthread_mutex_init( &stockm, NULL ); pthread_cond_init(&stockc, NULL ); pthread_create(&thre3, NULL, ui, NULL); pthread_create(&thre1, NULL, customer, NULL); // pthread_create(&thre4, NULL, customer2, NULL); pthread_create(&thre2, NULL, producer, NULL); pthread_join(thre1, NULL); pthread_join(thre2, NULL); pthread_join(thre3, NULL); // pthread_join(thre4, NULL); }