单生产单消费的环形队列模型

本文介绍了如何在C++中使用Makefile编译testMain.cc文件,涉及ringQueue模板类和semaphore的使用,展示了生产者-消费者模型在多线程环境中的应用。

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

Makefile

test:testMain.cc
	gcc -o test testMain.cc -std=c++11 -lpthread -lstdc++

.PHONY:clean
clean:
	rm -rf test

ringQueue.hpp

#ifndef _Ring_QUEUE_HPP_
#define _Ring_QUEUE_GPP_

#include <iostream>
#include <vector>
#include <pthread.h>
#include "sem.hpp"

const int g_default_num = 5;

template<class T>
class ringQueue
{
public:
    ringQueue(int default_num=g_default_num)
    :_ring_queue(default_num),
    _num(default_num),
    c_step(0),
    p_step(0),
    _space_sem(default_num),
    _data_sem(0)
    {}
    ~ringQueue()
    {}
    void push(const T& in)
    {
        _space_sem.p();
        _ring_queue[p_step++]=in;
        p_step%=_num;
        _data_sem.v();
    }
    void pop(T* out)
    {
        _data_sem.p();
        *out=_ring_queue[c_step++];
        c_step%=_num;
        _space_sem.v();
    }
    void debug()
    {
        std::cerr<<"size: "<<_ring_queue.size()<<" num: "<<_num<<std::endl;
    }
private:
    std::vector<T> _ring_queue;
    int _num;
    int c_step;//消费下标
    int p_step;//生产下标
    Sem _space_sem;
    Sem _data_sem;
};

#endif

sem.hpp

#ifndef _SEM_HPP_
#define _SEM_HPP_

#include <iostream>
#include <semaphore.h>

class Sem
{
public:
    Sem(int value)
    {
        sem_init(&_sem,0,value);
    }

    void p()
    {
        sem_wait(&_sem);
    }

    void v()
    {
        sem_post(&_sem);
    }

    ~Sem()
    {
        sem_destroy(&_sem);
    }
private:
    sem_t _sem;
};

#endif

testMain.cc

#include "ringQueue.hpp"
#include <cstdlib>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>
void* consumer(void* args)
{
    ringQueue<int>* rq=(ringQueue<int>*)args;
    while(true)
    {
        int x;
        //1.从环形队列中获取任务或数据
        rq->pop(&x);
        //2.进行一定的处理--不要忽略它的时间消耗问题
        std::cout<<"消费: "<<x<<std::endl;
        sleep(1);
    }
    return nullptr;
}

void* productor(void* args)
{
    ringQueue<int>* rq=(ringQueue<int>*)args;
    while(true)
    {
        //1.构建数据或者任务对象--一般是可以从外部来--不要忽略它的时间消耗问题
        int x=rand()%100+1;
        //2.推送到环形队列中
        rq->push(x);//完成生产过程
    }
    return nullptr;
}

int main()
{
    srand((uint64_t)time(nullptr)^getpid());
    pthread_t c,p;
    ringQueue<int>* rq=new ringQueue<int>(10);
    //rq->debug();
    pthread_create(&c,nullptr,consumer,(void*)rq);
    pthread_create(&p,nullptr,productor,(void*)rq);

    pthread_join(c,nullptr);
    pthread_join(p,nullptr);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值