代码
1 #include <stdio.h> 2 #include <pthread.h> 3 #include <stdlib.h> 4 #include <semaphore.h> 5 6 #define NUM 5 7 int queue[NUM]; 8 sem_t blank_number, product_number; 9 10 void *producer ( void * arg ) 11 { 12 static int p = 0; 13 14 for ( ;; ) { 15 sem_wait( &blank_number ); 16 queue[p] = rand() % 1000; 17 printf("Product %d \n", queue[p]); 18 p = (p+1) % NUM; 19 sleep ( rand() % 5); 20 sem_post( &product_number ); 21 } 22 } 23 void *consumer ( void * arg ) 24 { 25 26 static int c = 0; 27 for( ;; ) { 28 sem_wait( &product_number ); 29 printf("Consume %d\n", queue[c]); 30 c = (c+1) % NUM; 31 sleep( rand() % 5 ); 32 sem_post( &blank_number ); 33 } 34 } 35 36 int main(int argc, char *argv[] ) 37 { 38 pthread_t pid, cid; 39 40 sem_init( &blank_number, 0, NUM ); 41 sem_init( &product_number, 0, 0); 42 pthread_create( &pid, NULL, producer, NULL); 43 pthread_create( &cid, NULL, consumer, NULL); 44 pthread_join( pid, NULL ); 45 pthread_join( cid, NULL ); 46 sem_destroy( &blank_number ); 47 sem_destroy( &product_number ); 48 return 0; 49 }
运行结果

分析
功能:每一个生产者都要把自己生产的产品放入缓冲池,每个消费者从缓冲池中取走产品消费。在这种情况下,生产者消费者进程同步,因为只有通过互通消息才知道是否能存入产品或者取走产品。他们之间也存在互斥,即生产者消费者必须互斥访问缓冲池,即不能有两个以上的进程同时进行。
2.修改代码
1 #include <stdio.h> 2 #include <pthread.h> 3 #include <stdlib.h> 4 #include <semaphore.h> 5 6 #define NUM 3 7 int queue[NUM]; 8 sem_t blank_number, product_number; 9 10 void *producer ( void * arg ) 11 { 12 static int p = 0; 13 14 for ( ;; ) { 15 sem_wait( &blank_number ); 16 queue[p] = rand() % 6; 17 printf("Product %d \n", queue[p]); 18 p = (p+1) % NUM; 19 sleep ( rand() % 5); 20 sem_post( &product_number ); 21 } 22 } 23 void *consumer ( void * arg ) 24 { 25 26 static int c = 0; 27 for( ;; ) { 28 sem_wait( &product_number ); 29 printf("Consume %d\n", queue[c]); 30 c = (c+1) % NUM; 31 sleep( rand() % 5 ); 32 sem_post( &blank_number ); 33 } 34 } 35 36 int main(int argc, char *argv[] ) 37 { 38 pthread_t pid, cid; 39 40 sem_init( &blank_number, 0, NUM ); 41 sem_init( &product_number, 0, 0); 42 pthread_create( &pid, NULL, producer, NULL); 43 pthread_create( &cid, NULL, consumer, NULL); 44 pthread_join( pid, NULL ); 45 pthread_join( cid, NULL ); 46 sem_destroy( &blank_number ); 47 sem_destroy( &product_number ); 48 return 0; 49 }

浙公网安备 33010602011771号