基于环形队列的多生产多消费模型

2024-08-25 16:44

本文主要是介绍基于环形队列的多生产多消费模型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Linux中信号量相关接口及环形队列-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/2301_77479435/article/details/141411372

main.cc

#include"RingQueue.hpp"
#include"Task.hpp"
#include<pthread.h>
#include<ctime>
#include<cstdlib>
#include<sys/types.h>
#include<unistd.h>string SelfName()
{char name[128];snprintf(name,sizeof name,"thread[0x%x]",pthread_self());return name;
}//生产者线程和消费者线程那个限制性无法确定
void* ProductorRoutine(void* rq)
{RingQueue<Task>*ringqueue =static_cast<RingQueue<Task>* >(rq);while(true){//version1// int data=rand()%10+1;// ringqueue->Push(data);// cout<<"生产完成,生产的数据为: "<<data<<endl;//version2//构建任务int x=rand()%10;int y=rand()%5;char op=oper[rand()%oper.size()];Task t(x,y,op,mymath);//生产任务ringqueue->Push(t);//输出提示cout<<SelfName()<<", 生产者派发了一个任务: "<<t.toTaskString()<<endl;sleep(1);}
}
void* ConsumerRoutine(void* rq)
{RingQueue<Task>* ringqueue=static_cast<RingQueue<Task>* >(rq);while(true){//version1//  int data;//  ringqueue->Pop(&data);//  cout<<"消费完成, 消费的数据为: "<<data<<endl;Task t;ringqueue->Pop(&t);string result=t();cout<<SelfName()<<", 消费者消费了一个任务: "<<result<<endl;}
}
int main()
{srand((unsigned int)time(nullptr));RingQueue<Task>* rq=new RingQueue<Task>();//单生产,单消费,多生产,多消费 --> 只要保证,最终进入临界区的是一个生产,一个消费就行!!!pthread_t p[4],c[8];for(int i=0;i<4;i++)pthread_create(p+i,nullptr,ProductorRoutine,rq);for(int i=0;i<8;i++)pthread_create(c+i,nullptr,ConsumerRoutine,rq);for(int i=0;i<4;i++)pthread_join(p[i],nullptr);for(int i=0;i<8;i++)pthread_join(c[i],nullptr);delete rq;return 0;
}

Ringqueue.hpp

#pragma once#include<cassert>
#include<iostream>
#include<vector>
#include<semaphore.h>
#include<pthread.h>static const int gcap=5;
using namespace std;
template<class T>
class RingQueue
{void P(sem_t &sem){int n=sem_wait(&sem);assert(n==0);}void V(sem_t &sem){int n=sem_post(&sem);assert(n==0);}
public:RingQueue(const int& cap=gcap):_queue(cap),_cap(cap){int n=sem_init(&_spaceSem,0,_cap);assert(n==0);n=sem_init(&_dataSem,0,0);assert(n==0);_productorStep=_consumerStep=0;pthread_mutex_init(&_pmutex,nullptr);pthread_mutex_init(&_cmutex,nullptr);}//优化:提高信号量的并发度void Push(const T &in){P(_spaceSem);//申请到了空间信号量,意味着能进行正常生产pthread_mutex_lock(&_pmutex);//生产者生产时因保证环形队列不能为满_queue[_productorStep++]=in;_productorStep%=_cap;      pthread_mutex_unlock(&_pmutex);V(_dataSem);}void Pop(T* out){ P(_dataSem);pthread_mutex_lock(&_cmutex);    *out=_queue[_consumerStep++];_consumerStep%=_cap; pthread_mutex_unlock(&_cmutex);V(_spaceSem);}~RingQueue(){sem_destroy(&_spaceSem);sem_destroy(&_dataSem);pthread_mutex_destroy(&_pmutex);pthread_mutex_destroy(&_cmutex);}
private:vector<T> _queue;int _cap;//队列容量sem_t _spaceSem;//生产者看重空间资源sem_t _dataSem;//消费者看重数据资源int _productorStep;int _consumerStep;pthread_mutex_t _pmutex;pthread_mutex_t _cmutex;
};

Task.hpp

#pragma once#include<cstdio>
#include<iostream>
#include<string>
#include<functional>using namespace std;
class Task
{using func_t=function<int(int,int,char)>;//typedef function<int(int,int)> func_t;
public:Task(){}Task(int x,int y,char op,func_t func):_x(x),_y(y),_op(op),_callback(func){}string operator()(){int result=_callback(_x,_y,_op);//构建结构字符串char buffer[1024];snprintf(buffer,sizeof buffer,"%d %c %d = %d ",_x,_op,_y,result);return buffer;}string toTaskString(){char buffer[1024];snprintf(buffer,sizeof buffer,"%d %c %d = ? ",_x,_op,_y);return buffer;}
private:int _x;int _y;char _op;func_t _callback;
};
const string oper="+-*/";
int mymath(int x,int y,char op)
{int result=0;switch(op){case '+':result=x+y;break;case '-':result=x-y;break;case '*':result=x*y;break;case '/':{if(y==0){cerr<<"div zero error!!!"<<endl;result=-1;}elseresult=x/y;}break;case '%':{if(y==0){cerr<<"mod zero error!!!"<<endl;result=-1;}elseresult=x%y;}          break;default:break;}return result;
}
class SaveTask
{typedef function<void(const string&)> func_t;
public:SaveTask(){}SaveTask(const string &message,func_t func):_message(message),_func(func){}void operator()(){_func(_message);}
private:string _message;func_t _func;
};
void Save(const string& message)
{const string target="./log.txt";FILE* fp=fopen(target.c_str(),"a+");if(!fp){cerr<<" fopen error "<<endl;return;} fputs(message.c_str(),fp);fputs("\n",fp);fclose(fp);
}

这篇关于基于环形队列的多生产多消费模型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1106098

相关文章

0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型的操作流程

《0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeekR1模型的操作流程》DeepSeekR1模型凭借其强大的自然语言处理能力,在未来具有广阔的应用前景,有望在多个领域发... 目录0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型,3步搞定一个应

Deepseek R1模型本地化部署+API接口调用详细教程(释放AI生产力)

《DeepseekR1模型本地化部署+API接口调用详细教程(释放AI生产力)》本文介绍了本地部署DeepSeekR1模型和通过API调用将其集成到VSCode中的过程,作者详细步骤展示了如何下载和... 目录前言一、deepseek R1模型与chatGPT o1系列模型对比二、本地部署步骤1.安装oll

Spring AI Alibaba接入大模型时的依赖问题小结

《SpringAIAlibaba接入大模型时的依赖问题小结》文章介绍了如何在pom.xml文件中配置SpringAIAlibaba依赖,并提供了一个示例pom.xml文件,同时,建议将Maven仓... 目录(一)pom.XML文件:(二)application.yml配置文件(一)pom.xml文件:首

如何在本地部署 DeepSeek Janus Pro 文生图大模型

《如何在本地部署DeepSeekJanusPro文生图大模型》DeepSeekJanusPro模型在本地成功部署,支持图片理解和文生图功能,通过Gradio界面进行交互,展示了其强大的多模态处... 目录什么是 Janus Pro1. 安装 conda2. 创建 python 虚拟环境3. 克隆 janus

本地私有化部署DeepSeek模型的详细教程

《本地私有化部署DeepSeek模型的详细教程》DeepSeek模型是一种强大的语言模型,本地私有化部署可以让用户在自己的环境中安全、高效地使用该模型,避免数据传输到外部带来的安全风险,同时也能根据自... 目录一、引言二、环境准备(一)硬件要求(二)软件要求(三)创建虚拟环境三、安装依赖库四、获取 Dee

解读Redis秒杀优化方案(阻塞队列+基于Stream流的消息队列)

《解读Redis秒杀优化方案(阻塞队列+基于Stream流的消息队列)》该文章介绍了使用Redis的阻塞队列和Stream流的消息队列来优化秒杀系统的方案,通过将秒杀流程拆分为两条流水线,使用Redi... 目录Redis秒杀优化方案(阻塞队列+Stream流的消息队列)什么是消息队列?消费者组的工作方式每

DeepSeek模型本地部署的详细教程

《DeepSeek模型本地部署的详细教程》DeepSeek作为一款开源且性能强大的大语言模型,提供了灵活的本地部署方案,让用户能够在本地环境中高效运行模型,同时保护数据隐私,在本地成功部署DeepSe... 目录一、环境准备(一)硬件需求(二)软件依赖二、安装Ollama三、下载并部署DeepSeek模型选

Golang的CSP模型简介(最新推荐)

《Golang的CSP模型简介(最新推荐)》Golang采用了CSP(CommunicatingSequentialProcesses,通信顺序进程)并发模型,通过goroutine和channe... 目录前言一、介绍1. 什么是 CSP 模型2. Goroutine3. Channel4. Channe

Redis延迟队列的实现示例

《Redis延迟队列的实现示例》Redis延迟队列是一种使用Redis实现的消息队列,本文主要介绍了Redis延迟队列的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习... 目录一、什么是 Redis 延迟队列二、实现原理三、Java 代码示例四、注意事项五、使用 Redi

将Python应用部署到生产环境的小技巧分享

《将Python应用部署到生产环境的小技巧分享》文章主要讲述了在将Python应用程序部署到生产环境之前,需要进行的准备工作和最佳实践,包括心态调整、代码审查、测试覆盖率提升、配置文件优化、日志记录完... 目录部署前夜:从开发到生产的心理准备与检查清单环境搭建:打造稳固的应用运行平台自动化流水线:让部署像