编写C语言程序,以生产者、消费者典型同步问题为例实现。设有一个生产者和一个消费者,缓冲区可以存放产品,生产者不断地生产产品,消费者不断地消费产品。设置三个信号量,一个互斥信号量初值为1,对缓冲区资源进行互斥
时间: 2024-11-25 08:13:43 浏览: 64
在C语言中,我们可以使用`pthread.h`库来模拟生产者-消费者模型,利用信号量来解决同步问题。下面是一个简单的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 5
#define MAX_PRODUCTS -1
typedef struct {
int buffer[BUFFER_SIZE];
int count;
int producer_index;
int consumer_index;
pthread_mutex_t mutex; // 互斥锁
pthread_cond_t empty; // 当缓冲区为空时唤醒消费者
pthread_cond_t full; // 当缓冲区满时唤醒生产者
} ProductBuffer;
void* producer(void* arg) {
ProductBuffer* buffer = (ProductBuffer*)arg;
while (1) {
pthread_mutex_lock(&buffer->mutex);
if (buffer->count == BUFFER_SIZE) {
printf("Producer waiting because buffer is full.\n");
pthread_cond_wait(&buffer->full, &buffer->mutex);
}
buffer->buffer[buffer->producer_index] = ++buffer->count;
buffer->producer_index = (buffer->producer_index + 1) % BUFFER_SIZE;
buffer->count %= BUFFER_SIZE; // 防止溢出
printf("Produced product %d, buffer count now %d.\n", buffer->count, buffer->buffer[buffer->consumer_index]);
pthread_mutex_unlock(&buffer->mutex);
// 生产者需要通知消费者缓冲区有新的产品
if (buffer->count > 0)
pthread_cond_signal(&buffer->empty);
}
}
void* consumer(void* arg) {
ProductBuffer* buffer = (ProductBuffer*)arg;
while (1) {
pthread_mutex_lock(&buffer->mutex);
if (buffer->count == 0) {
printf("Consumer waiting because buffer is empty.\n");
pthread_cond_wait(&buffer->empty, &buffer->mutex);
}
buffer->consumer_index = (buffer->consumer_index + 1) % BUFFER_SIZE;
buffer->count++;
printf("Consumed product %d, buffer count now %d.\n", buffer->count, buffer->buffer[buffer->consumer_index]);
pthread_mutex_unlock(&buffer->mutex);
// 消费者处理完产品后告诉生产者
if (buffer->count < BUFFER_SIZE)
pthread_cond_signal(&buffer->full);
}
}
int main() {
ProductBuffer buffer;
for (int i = 0; i < BUFFER_SIZE; i++) {
buffer.buffer[i] = 0;
}
buffer.count = 0;
buffer.producer_index = 0;
buffer.consumer_index = 0;
pthread_mutex_init(&buffer.mutex, NULL);
pthread_cond_init(&buffer.empty, NULL);
pthread_cond_init(&buffer.full, NULL);
pthread_t producer_thread, consumer_thread;
pthread_create(&producer_thread, NULL, producer, &buffer);
pthread_create(&consumer_thread, NULL, consumer, &buffer);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
return 0;
}
```
在这个示例中,我们创建了两个线程,一个生产者和一个消费者。它们共享一个缓冲区,并通过互斥锁(`mutex`)和条件变量(`cond`)协调操作。当缓冲区满时,生产者等待并由消费者唤醒;反之亦然。
阅读全文