条件变量和生产者消费模式

本文详细解析了基于C语言的生产者消费者模型实现,利用pthread库中的互斥锁和条件变量来同步线程,确保数据的一致性和线程间的通信。通过生产者线程不断生成产品并通知消费者线程进行消费,展示了线程间如何高效协作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

int ready = 0;
pthread_mutex_t mutex;
pthread_cond_t has_product;
         
void* producer(void* arg) {
        int no = (int)arg;
        printf("no %d, producer start!\n");
        // 条件变量
        for(;;) {
           // printf("producer start!\n");
           pthread_mutex_lock(&mutex);
           // 往队列中添加产品 
           ready++; 
           printf("producer %d, produce product\n",no);
           // fflush(NULL);
           // 通知消费者,有新的产品可以消费了
           // 会阻塞输出
           pthread_cond_signal(&has_product);
           printf("producer %d, signal\n", no);
           pthread_mutex_unlock(&mutex);
           sleep(1);
        }
}

// 消费者
void* consumer(void* arg) {
        for(;;) {
           pthread_mutex_lock(&mutex);
           // while?
           while(ready == 0) {
              // 没有产品,继续等待
              printf("consume wait!\n");
              pthread_cond_wait(&has_product, &mutex);
              printf("consume wait end!");
           }
           // 有产品,消费产品
           ready--;
           printf("consume product\n");
           pthread_mutex_unlock(&mutex);
           sleep(1);
        }
}

void main() {
// 
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&has_product, NULL);
printf("init\n");
pthread_t tid_p = NULL;
pthread_t tid_c = NULL;

pthread_create(&tid_c,NULL,consumer,NULL);
sleep(1);
pthread_create(&tid_p,NULL,producer,NULL);

pthread_join(tid_p, NULL);
pthread_join(tid_c, NULL);

pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&has_product);

}
                                      

备注:

1、上述代码是基于c实现的。linux编译指令一般为gcc xx.c -o xx,因为代码使用pthread,情况有点特殊,此处编译指令为:gcc xx.c -o xx -lpthread。否则编译会报错。

2、如果大家对代码中引用的<pthread.h>定义的接口理解的不深。可以怀疑这段代码可能会产生死锁。从而对运行结果产生困惑。拨开云雾见天日出路在对pthread_cond_wait(&has_product, &mutex);的理解。(我的理解可能有错,pthread_cond_wait在producer没有发出pthread_cond_signal时会在解锁和加锁中来回操作)。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值