#include <pthread.h> #include <stdio.h> #include <semaphore.h> #include <string.h> #include <stdlib.h> #define BUFF_SIZE 10 char buffer[BUFF_SIZE]; char count = 0; //缓冲池里的信息数目 sem_t sem_mutex; //生产者和消费者的相互排斥锁 sem_t p_sem_mutex; //空的时候,对消费者不可进 sem_t c_sem_mutex; //满的时候,对生产者不可进 /* * @brief 步骤,用sem_mutex锁住count,推断count的大小,能否够继续放数据。假设count = 10则锁住p_sem_mutex * 假设count < 10则释放p_sem_mutex锁 */ void* produce() { while (1) { sem_wait(&sem_mutex); //等待缓冲池空暇 if (count == BUFF_SIZE) { sem_post(&c_sem_mutex); sem_post(&sem_mutex); continue; } sem_wait(&p_sem_mutex); //当缓冲池未满 buffer[count] = 'A'; printf("produce: buffer: %s count: %d ", buffer, count); fflush(stdout); count++; if (count < BUFF_SIZE) //缓冲池未满 { sem_post(&p_sem_mutex); } if (count > 0) //缓冲池未空 { sem_post(&c_sem_mutex); } sem_post(&sem_mutex); //sleep(1); } } void* consumer() { while (1) { sem_wait(&sem_mutex); if (count == 0) { sem_post(&p_sem_mutex); sem_post(&sem_mutex); continue; } sem_wait(&c_sem_mutex);<pre name="code" class="cpp"> buffer[count] = '