下面是一个使用C语言模拟生产者消费者算法的示例:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 10 // 缓冲区大小
#define NUM_PRODUCERS 3 // 生产者数量
#define NUM_CONSUMERS 2 // 消费者数量
#define NUM_ITEMS 20 // 要生产的项目数量
int buffer[BUFFER_SIZE]; // 缓冲区数组
int in = 0; // 插入位置指针
int out = 0; // 移出位置指针
int count = 0; // 缓冲区中的项目数量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 互斥锁
pthread_cond_t full = PTHREAD_COND_INITIALIZER; // 缓冲区满条件变量
pthread_cond_t empty = PTHREAD_COND_INITIALIZER; // 缓冲区空条件变量
void *producer(void *arg)
{
int i;
int producer_id = *(int *)arg;
for (i = 0; i < NUM_ITEMS; ++i) {
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) {
pthread_cond_wait(&full, &mutex);
}
buffer[in] = i;
in = (in + 1) % BUFFER_SIZE;
count++;
printf("Producer %d produced item %d\n", producer_id, i);
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void *consumer(void *arg)
{
int i;
int consumer_id = *(int *)arg;
for (i = 0; i < NUM_ITEMS / NUM_CONSUMERS; ++i) {
pthread_mutex_lock(&mutex);
while (count == 0) {
pthread_cond_wait(&empty, &mutex);
}
int item = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
printf("Consumer %d consumed item %d\n", consumer_id, item);
pthread_cond_signal(&full);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main()
{
int i;
pthread_t producers[NUM_PRODUCERS];
pthread_t consumers[NUM_CONSUMERS];
int producer_ids[NUM_PRODUCERS];
int consumer_ids[NUM_CONSUMERS];
for (i = 0; i < NUM_PRODUCERS; ++i) {
producer_ids[i] = i;
pthread_create(&producers[i], NULL, producer, &producer_ids[i]);
}
for (i = 0; i < NUM_CONSUMERS; ++i) {
consumer_ids[i] = i;
pthread_create(&