使用信号量实现生产者消费者问题

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#include <queue>

/**
 * 生产者和消费者问题
 * 使用信号量实现生产者和消费者模型,生产者有5个,消费者也有5个。
 */

#define MAX_SIZE 10

sem_t empty;           // 信号量empty,表示缓冲区中空闲位置
sem_t full;            // 信号量full,表示缓冲区中资源个数
pthread_mutex_t mutex; // 互斥锁实现的buf的互斥访问

// 缓冲区
std::queue<int> buf;

// 生产者进程
void *producer(void *arg)
{
    while (1)
    {
        // 当缓冲区不满时,向缓冲区内生产
        sem_wait(&empty);
        pthread_mutex_lock(&mutex); // 如果加锁操作放到sem_wait前面有可能会产生死锁

        buf.push(10);
        std::cout << pthread_self() << " producer product  cur size " << buf.size() << std::endl;

        pthread_mutex_unlock(&mutex);
        sem_post(&full);

        sleep(2);
    }
    return NULL;
}

// 消费者进程
void *consumer(void *arg)
{
    while (1)
    {
        sem_wait(&full);
        pthread_mutex_lock(&mutex); // 如果加锁操作放到sem_wait前面有可能会产生死锁

        // 拿走一个产品
        int res = buf.front();
        buf.pop();
        std::cout << pthread_self() << " consumer get is " << res << "cur size " << buf.size() << std::endl;

        pthread_mutex_unlock(&mutex);
        sem_post(&empty);

        sleep(2);
    }
    return NULL;
}

int main()
{
    pthread_t consumers[5];
    pthread_t producers[5];

    // 信号量初始化
    sem_init(&empty, 0, MAX_SIZE); // 初始空闲个数为MAX_SIZE
    sem_init(&full, 0, 0);         // 初始资源个数为0

    pthread_mutex_init(&mutex, NULL);

    for (int i = 0; i < 5; i++)
    {
        // 创建生产者线程
        pthread_create(&producers[i], NULL, producer, NULL);
    }

    for (int i = 0; i < 5; i++)
    {
        // 创建消费者线程
        pthread_create(&consumers[i], NULL, consumer, NULL);
    }

    // 回收线程
    for (int i = 0; i < 5; i++)
    {
        pthread_join(producers[i], NULL);
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_join(consumers[i], NULL);
    }

    // 条件变量销毁
    sem_destroy(&empty);
    sem_destroy(&full);
    pthread_mutex_destroy(&mutex);

    return 0;
}
``
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值