c语言实现消费者问题
时间: 2023-10-06 15:13:46 浏览: 70
消费者问题是指一个生产者(Producer)和一个消费者(Consumer)在同一个缓冲区(Buffer)进行数据交互的问题。下面是一个使用 C 语言实现的消费者问题示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int in = 0, out = 0;
sem_t empty_sem, full_sem;
pthread_mutex_t mutex;
void *producer(void *arg)
{
int i;
for (i = 0; i < 20; i++) {
sem_wait(&empty_sem);
pthread_mutex_lock(&mutex);
buffer[in] = i;
printf("Producer produces the item %d at position %d\n", buffer[in], in);
in = (in + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&full_sem);
}
}
void *consumer(void *arg)
{
int i, item;
for (i = 0; i < 20; i++) {
sem_wait(&full_sem);
pthread_mutex_lock(&mutex);
item = buffer[out];
printf("Consumer consumes the item %d at position %d\n", item, out);
out = (out + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&empty_sem);
}
}
int main()
{
pthread_t pid, cid;
sem_init(&empty_sem, 0, BUFFER_SIZE);
sem_init(&full_sem, 0, 0);
pthread_mutex_init(&mutex, NULL);
pthread_create(&pid, NULL, producer, NULL);
pthread_create(&cid, NULL, consumer, NULL);
pthread_join(pid, NULL);
pthread_join(cid, NULL);
sem_destroy(&empty_sem);
sem_destroy(&full_sem);
pthread_mutex_destroy(&mutex);
return 0;
}
```
在这个示例中,生产者和消费者线程分别通过 `pthread_create` 函数创建,并分别执行 `producer` 和 `consumer` 函数。在 `main` 函数中,通过 `pthread_join` 函数等待线程结束。
这里用到了信号量和互斥锁来保证线程之间的同步和互斥。其中 `empty_sem` 表示缓冲区的空闲空间数量,`full_sem` 表示缓冲区中已有的数据数量,`mutex` 表示互斥锁。
在生产者和消费者的函数实现中,使用 `sem_wait` 和 `sem_post` 函数来操作信号量,使用 `pthread_mutex_lock` 和 `pthread_mutex_unlock` 函数来操作互斥锁。在生产者函数中,当缓冲区已满时,会调用 `sem_wait` 函数阻塞当前线程,直到有空闲空间;在消费者函数中,当缓冲区为空时,会调用 `sem_wait` 函数阻塞当前线程,直到有数据可取。
在操作缓冲区时,使用循环队列的方式来实现,通过 `in` 和 `out` 指针来指示当前位置。在每次插入或取出数据后,将指针向后移动,当指针到达缓冲区的末尾时,将其置为 0,形成循环队列的效果。
阅读全文
相关推荐

















