用C语言编程实现生产者-消费者问题,用word文档提交可运行的源代码,并给出运行效果截图。
时间: 2024-10-22 15:29:48 浏览: 43
毕业设计用单片机AT89S8252实现温度远程显示word文档
生产者-消费者问题是经典的并发控制问题,通常用于演示线程同步的概念。在C语言中,我们可以使用互斥锁(mutex)和条件变量(condition variables)来解决这个问题。下面是一个简化版的生产者-消费者模型的示例,我将提供伪代码解释,但由于此处无法创建实际的word文档、源代码文件或截图,你可以在本地尝试编写并测试。
```c
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 5
#define SEMAPHORE_PRODUCER 1
#define SEMAPHORE_CONSUMER 2
typedef struct {
int buffer[BUFFER_SIZE];
int count;
int in;
int out;
pthread_mutex_t mutex;
sem_t producer_semaphore;
sem_t consumer_semaphore;
} Buffer;
void* producer(void* arg) {
Buffer* buffer = (Buffer*)arg;
while (1) {
// 生产者获取资源
pthread_mutex_lock(&buffer->mutex);
if (buffer->count == BUFFER_SIZE) {
sem_wait(&buffer->producer_semaphore); // 阻塞直到有空位
}
buffer->buffer[buffer->in] = rand(); // 生产元素
buffer->count++;
buffer->in = (buffer->in + 1) % BUFFER_SIZE; // 循环索引
pthread_mutex_unlock(&buffer->mutex);
// 提醒消费者产品可用
sem_post(&buffer->consumer_semaphore);
}
}
void* consumer(void* arg) {
Buffer* buffer = (Buffer*)arg;
while (1) {
// 消费者等待产品
pthread_mutex_lock(&buffer->mutex);
if (buffer->count == 0) {
sem_wait(&buffer->consumer_semaphore); // 阻塞直到有产品
}
printf("Consumed %d\n", buffer->buffer[buffer->out]); // 消费并打印
buffer->count--;
buffer->out = (buffer->out + 1) % BUFFER_SIZE; // 循环索引
pthread_mutex_unlock(&buffer->mutex);
// 通知生产者空间已满
sem_post(&buffer->producer_semaphore);
}
}
int main() {
Buffer buffer;
init_buffer(buffer);
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;
}
```
阅读全文