通过互斥锁Mutex和条件变量Conditions实现动态平衡,模拟生活中卖包子的情景

实现代码如下:

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值