#include<stdio.h> #include<stdlib.h> #include<pthread.h> #include<semaphore.h> #include<sys/types.h> #define M 10 // 缓冲区容量为10 void *productor(void *ptr); // 消费者线程 void *customer(void *ptr); // 生产者线程 void produce(); // 生产过程 void consume(); // 消费过程 sem_t productor_sem; // 生产者的信号量 sem_t customer_sem; // 消费者的信号量 sem_t mutex_sem; // 互斥信号量,保证一次只有一个线程访问缓冲区 int in = 0; // 生产者放产品的位置 int out = 0; // 消费者取产品的位置 int *buffer = NULL; // 缓冲区 int main() { buffer = (int *)malloc(M * sizeof(int)); // 缓冲区 pthread_t thread1,thread2; // 这里设定刚开始缓冲区为空 sem_init(&productor_sem, 0, M); sem_init(&customer_sem, 0, 0); sem_init(&mutex_sem, 0, 1); pthread_create(&thread1, NULL, productor, NULL); pthread_create(&thread2, NULL, customer, NULL); pthread_join(thread1, NULL); pthread_join(thread2, NULL); return 0; } void *productor(void *ptr) { while(1) { sem_wait(&productor_sem); sem_wait(&mutex_sem); produce(); //生产产品 sem_post(&mutex_sem); sem_post(&customer_sem); sleep(2); } } void *customer(void *ptr) { while(1) { sem_wait(&customer_sem); sem_wait(&mutex_sem); consume(); // 消费产品 sem_post(&mutex_sem); sem_post(&productor_sem); sleep(8); } } void produce() { static int data = 0; buffer[in] = ++data; printf("%d 已被放入缓冲区\n", data); in = (in + 1) % (M + 1); } void consume() { int fetch = buffer[out]; out = (out + 1) % (M + 1); printf("%d 已被取出\n", fetch); }