其他分享
首页 > 其他分享> > 生产者消费者问题:条件变量实现和信号量实现

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

作者:互联网

条件变量实现:记一次由虚假唤醒产生的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;
}

标签:include,实现,create,信号量,生产者,full,pthread,sem,NULL
来源: https://www.cnblogs.com/rookiezjz/p/15831099.html