生产者消费者问题:条件变量实现和信号量实现

条件变量实现:记一次由虚假唤醒产生的bug

信号量实现:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
sem_t empty, full;

void *produce(void *s)
{
    while(1)
    {
        usleep(100000);
        sem_wait(&empty);
        int a = 0;
        sem_getvalue(&full, &a);
        printf("%s生产后有%d个产品\n",(char*)s, a+1);
        sem_post(&full);
    }
    
    return NULL;
}

void *consume(void *s)
{
    usleep(200000);
    while(1) 
    {
        usleep(100000);
        sem_wait(&full);
        int a = 0;
        sem_getvalue(&full, &a);
        printf("%s消费后有%d个产品\n",(char*)s, a);
        sem_post(&empty);
    }

    return NULL;
}

int main() {
    {//初始化
        pthread_t p1, p2, p3, c1, c2, c3;
        sem_init(&empty, 0, 10);
        sem_init(&full, 0, 0);

        pthread_create(&p1, NULL, produce, "生产者一");
        pthread_create(&p2, NULL, produce, "生产者二");
        pthread_create(&p3, NULL, produce, "生产者三");
        pthread_create(&c1, NULL, consume, "消费者一");
        pthread_create(&c2, NULL, consume, "消费者二");
        pthread_create(&c3, NULL, consume, "消费者三");
        pthread_detach(p1);
        pthread_detach(p2);
        pthread_detach(p3);
        pthread_detach(c1);
        pthread_detach(c2);
        pthread_detach(c3);
    }
    
    sleep(3);
    sem_destroy(&empty);
    sem_destroy(&full);
    return 0;
}
posted @   hellozhangjz  阅读(82)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示