实现代码如下:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define P_C 3 //3个生产者
#define C_C 2 //2个消费者
int count = 0; //馒头的个数
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *consume(void *arg)
{
while (1)
{
//观察是否有馒头可以吃,需要独占盆子
pthread_mutex_lock(&mutex);
while (count == 0)
{
//没有馒头可以吃,让阿姨生产
printf("%lu cosumer is waitting\n", pthread_self());
//去等着
pthread_cond_wait(&cond, &mutex);
//自动释放锁, 并且再条件变量上阻塞
//唤醒的时候,自动去抢锁
}
//吃馒头
count--;
printf("%lu cosumer is consuming, count is %d\n", pthread_self(), count);
//释放锁
pthread_mutex_unlock(&mutex);
sleep(2);
}
return NULL;
}
void *produce(void *arg)
{
while (1)
{
//阿姨生产馒头, 独占盆子
pthread_mutex_lock(&mutex);
//盆子放的下才生产馒头
if (count >= 5)
{
printf("too much waitting for consume\n");
pthread_mutex_unlock(&mutex);
sleep(1);
continue;
}
printf("%lu starting produce, now count is %d\n", pthread_self(), count);
count++;
printf("after produce, count is %d\n", count);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(2);
}
}
int main()
{
pthread_t pid[P_C], cid[C_C];
int i;
for (i = 0; i < C_C; i++)
{
if (0 != pthread_create(&cid[i], NULL, consume, NULL))
{
perror("c");
exit(1);
}
}
for (i = 0; i < P_C; i++)
{
if (0 != pthread_create(&pid[i], NULL, produce, NULL))
{
perror("p");
exit(1);
}
}
for (i = 0; i < C_C; i++)
{
pthread_join(cid[i], NULL);
}
for (i = 0; i < P_C; i++)
{
pthread_join(pid[i], NULL);
}
return 0;
}
本文介绍了一个使用多线程实现的生产者消费者模型案例。通过C语言结合POSIX线程库,模拟了三个生产者和两个消费者在一个有限容量的缓冲区中进行生产和消费的过程。该模型利用互斥锁和条件变量来确保线程间的同步与通信。
904

被折叠的 条评论
为什么被折叠?



