Linux C系统编程——条件变量实现生产者,消费者问题(只需要两分钟你就能看懂)

一切想表达的都在代码和注释里了

只需要两分钟你就能看懂

源码

//利用条件变量实现生产者,消费者问题
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
//定义一把锁
pthread_mutex_t mutex1=PTHREAD_MUTEX_INITIALIZER;
//定义一个条件
pthread_cond_t cond1=PTHREAD_COND_INITIALIZER;

typedef struct table{
    struct table *next;
    int num;
} ST;

//定义头节点
ST *head;

void producer(){
    while (1){
        ST *food;
        food=malloc(sizeof(struct table));
        pthread_mutex_lock(&mutex1);//对桌子加锁
        food->num=rand()%1000+1;//随机生成一个数
        //头插法将生产的数据发送到桌子上
        food->next=head;
        head=food;
        printf("------producer is: %d\n",food->num);
        pthread_mutex_unlock(&mutex1);//释放锁
        pthread_cond_signal(&cond1);//发送已经生产的条件
        sleep(rand()%3);
    }
}
void consumer(){
    while (1){
        ST *food;
        pthread_mutex_lock(&mutex1);
        if (head==NULL){
            pthread_cond_wait(&cond1,&mutex1);//桌子上没有东西,就阻塞
        }
        food=head;
        head=NULL;
        printf("------consumer is: %d\n",food->num);
        pthread_mutex_unlock(&mutex1);
        free(food);
        sleep(rand()%3);
    }
}
int main(void){
    //创建两个线程,生产者,消费者
    pthread_t tid1,tid2;
    while ((pthread_create(&tid1,NULL,(void *)producer,NULL))!=0);
    while ((pthread_create(&tid2,NULL,(void *)consumer,NULL))!=0);

    //回收线程
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);

    return 0;

}

实验结果

在这里插入图片描述
(最好是根据实验现象分析其中的原理)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jacky~~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值