Linux C pthread mutex 互斥

pthread_mutex_t是一个互斥量

互斥量:只有两种值0/1 被访问/未被访问

pthread_cond_t是来wait 和 wakeup的
在这里插入图片描述

现代操作系统中的 代码

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define MAX 1000000000
pthread_mutex_t the_mutex;
pthread_cond_t condc,condp;
int buffer = 0;// 缓冲区

void *Producer(void *ptr)
{
    for(int i = 0;i<=MAX;i++)
    {
        pthread_mutex_lock(&the_mutex);
        while(buffer!=0)pthread_cond_wait(&condp,&the_mutex);
        buffer = i;
        printf("Producer %d",buffer);
        pthread_cond_signal(&condc);//唤醒消费者
        pthread_mutex_unlock(&the_mutex);
    }
    pthread_exit(0);
}
void *Consumer(void *ptr)
{
    for(int i =0 ;i<=MAX;i++)
    {
        pthread_mutex_lock(&the_mutex);
        while(buffer ==0 ) pthread_cond_wait(&condc,&the_mutex);
        buffer = 0;
        printf("Consumer %d",buffer);
        pthread_cond_signal(&condp);
        pthread_mutex_unlock(&the_mutex);
    }
    pthread_exit(0);
}

int main(void)
{
    pthread_t pro,con;
    pthread_mutex_init(&the_mutex,0);
    pthread_cond_init(&condc,0);
    pthread_cond_init(&condp,0);
    pthread_create(&con,0,Consumer,0);
    pthread_create(&pro,0,Producer,0);
    pthread_join(pro,0);
    pthread_join(con,0);
    pthread_cond_destroy(&condc);
    pthread_cond_destroy(&condp);
    pthread_mutex_destroy(&the_mutex);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值