写一个c语言管程解决生产者消费者问题的代码程序
时间: 2024-09-26 16:09:37 浏览: 66
在C语言中,我们可以使用互斥锁(mutex)、条件变量(condition variable)和信号量(semaphore)来解决生产者-消费者问题。这里是一个简单的基于Pthreads库的示例:
```c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_BUFFER 10
#define SEMAPHORE_INIT 1
typedef struct {
int buffer[MAX_BUFFER];
int count;
int in_prod;
int in_cons;
pthread_mutex_t mutex; // 互斥锁
pthread_cond_t empty, full; // 条件变量
sem_t semaphore_buffer, semaphore_prod, semaphore_cons;
} Buffer;
void* producer(void* arg) {
Buffer* buffer = (Buffer*)arg;
while (1) {
pthread_mutex_lock(&buffer->mutex);
if (buffer->count == MAX_BUFFER) {
pthread_cond_wait(&buffer->full, &buffer->mutex);
}
buffer->buffer[buffer->in_prod] = buffer->count++;
buffer->in_prod = (buffer->in_prod + 1) % MAX_BUFFER;
printf("Producer produced item %d\n", buffer->count);
pthread_mutex_unlock(&buffer->mutex);
}
return NULL;
}
void* consumer(void* arg) {
Buffer* buffer = (Buffer*)arg;
while (1) {
pthread_mutex_lock(&buffer->mutex);
if (buffer->count == 0) {
pthread_cond_wait(&buffer->empty, &buffer->mutex);
}
buffer->count--;
buffer->in_cons = (buffer->in_cons + 1) % MAX_BUFFER;
printf("Consumer consumed item %d\n", buffer->count);
pthread_mutex_unlock(&buffer->mutex);
}
return NULL;
}
int main() {
Buffer buffer;
for (int i = 0; i < MAX_BUFFER; i++) {
buffer.buffer[i] = -1;
}
buffer.count = 0;
buffer.in_prod = 0;
buffer.in_cons = 0;
pthread_init(&buffer.semaphore_buffer, NULL, SEMAPHORE_INIT);
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`确保线程之间的同步。当缓冲区满或空时,线程会等待直到条件满足。
阅读全文