程式碼見《現代作業系統》 第3版。
為了顯示效果,新增了printf()函式來顯示執行效果
1 #include<stdio.h> 2 #include<pthread.h> 3 #define MAX 20 4 pthread_mutex_t the_mutex; 5 pthread_cond_t condc, condp; 6 int buffer = 0; 7 8 void *producer(void *ptr) 9 { 10 int i; 11 for(i = 1; i <= MAX; i++) 12 { 13 pthread_mutex_lock(&the_mutex); 14 while(buffer != 0) pthread_cond_wait(&condp, &the_mutex); 15 buffer = i; 16 printf("%d ", buffer); 17 pthread_cond_signal(&condc); 18 pthread_mutex_unlock(&the_mutex); 19 } 20 pthread_exit(0); 21 } 22 23 void *consumer(void *ptr) 24 { 25 int i; 26 for(i = 1; i < MAX; i++) 27 { 28 pthread_mutex_lock(&the_mutex); 29 while(buffer == 0)pthread_cond_wait(&condc, &the_mutex); 30 buffer = 0; 31 printf("%d ", buffer); 32 pthread_cond_signal(&condp); 33 pthread_mutex_unlock(&the_mutex); 34 } 35 pthread_exit(0); 36 } 37 38 int main(void) 39 { 40 pthread_t pro, con; 41 pthread_mutex_init(&the_mutex, 0); 42 pthread_cond_init(&condc, 0); 43 pthread_cond_init(&condp, 0); 44 pthread_create(&con, 0, consumer, 0); 45 pthread_create(&pro, 0, producer, 0); 46 pthread_join(pro, 0); 47 pthread_join(con, 0); 48 pthread_cond_destroy(&condc); 49 pthread_cond_destroy(&condp); 50 pthread_mutex_destroy(&the_mutex); 51 }
編譯命令
gcc -lpthread -o procro procro.c
執行後的效果如: