【Linux】多线程_6

文章目录

  • 九、多线程
    • 7. 生产者消费者模型
      • 生产者消费者模型的简单代码
      • 结果演示
  • 未完待续


九、多线程

7. 生产者消费者模型

生产者消费者模型的简单代码

Makefile

cp:Main.ccg++ -o $@ $^ -std=c++11 -lpthread
.PHONY:clean
clean:rm -f cp

Thread.hpp

#ifndef __THREAD_HPP__
#define __THREAD_HPP__#include <iostream>
#include <string>
#include <unistd.h>
#include <functional>
#include <pthread.h>namespace ThreadModule
{template<typename T>using func_t = std::function<void(T&)>;template<typename T>class Thread{public:void Excute(){_func(_data);}public:Thread(func_t<T> func, T& data, const std::string &name="none-name"): _func(func), _data(data), _threadname(name), _stop(true){}static void *threadroutine(void *args){Thread<T> *self = static_cast<Thread<T> *>(args);self->Excute();return nullptr;}bool Start(){int n = pthread_create(&_tid, nullptr, threadroutine, this);if(!n){_stop = false;return true;}else{return false;}}void Detach(){if(!_stop){pthread_detach(_tid);}}void Join(){if(!_stop){pthread_join(_tid, nullptr);}}std::string name(){return _threadname;}void Stop(){_stop = true;}~Thread() {}private:pthread_t _tid;std::string _threadname;T& _data;func_t<T> _func;bool _stop;};
}#endif

BlockQueue.hpp

#ifndef __BLOCKQUEUE_HPP__
#define __BLOCKQUEUE_HPP__#include <iostream>
#include <string>
#include <queue>
#include <pthread.h>template<typename T>
class BlockQueue
{
private:bool IsFull() const{return _block_queue.size() == _cap;}bool IsEmpty() const{return _block_queue.empty();}
public:BlockQueue(int cap):_cap(cap){_productor_wait_num = 0;_consumer_wait_num = 0;// 初始化互斥锁pthread_mutex_init(&_mutex, nullptr);// 初始化条件变量pthread_cond_init(&_productor_cond, nullptr); // 初始化条件变量pthread_cond_init(&_consumer_cond, nullptr);}// 生产者使用的入队列接口void Enqueue(const T& in){// 加锁pthread_mutex_lock(&_mutex);while (IsFull()){// 生产者等待数量加1_productor_wait_num++;// 等待条件变量通知唤醒并竞争到互斥锁pthread_cond_wait(&_productor_cond, &_mutex);// 生产者等待数量减1_productor_wait_num--;}// 生产的数据入资源队列_block_queue.push(in);// 解锁pthread_mutex_unlock(&_mutex);// 通知消费者可以从等待队列中出队列if (_consumer_wait_num > 0) pthread_cond_signal(&_consumer_cond);}// 消费者使用的出队列接口void Pop(T* out){// 加锁pthread_mutex_lock(&_mutex);while (IsEmpty()){// 消费者等待数量加1_consumer_wait_num++;// 等待条件变量通知唤醒并竞争到互斥锁pthread_cond_wait(&_consumer_cond, &_mutex);// 消费者等待数量减1_consumer_wait_num--;}// 获取数据*out = _block_queue.front();// 数据出队列_block_queue.pop();// 解锁pthread_mutex_unlock(&_mutex);// 通知生产者可以从等待队列中出队列if (_productor_wait_num > 0) pthread_cond_signal(&_productor_cond);}~BlockQueue(){// 销毁互斥锁pthread_mutex_destroy(&_mutex);// 销毁条件变量pthread_cond_destroy(&_productor_cond);// 销毁条件变量pthread_cond_destroy(&_consumer_cond);}
private:std::queue<T> _block_queue;// 容量上限int _cap;// 互斥锁pthread_mutex_t _mutex;// 条件变量,用于通知生产者可以入队列pthread_cond_t _productor_cond;// 条件变量,用于通知消费者可以出队列pthread_cond_t _consumer_cond;// 生产者等待数量int _productor_wait_num;// 消费者等待数量int _consumer_wait_num;
};#endif

Task.hpp

#pragma once#include <iostream>
#include <string>class Task
{
public:Task(){}Task(int a, int b):_a(a),_b(b),_result(0){}// 执行任务void Execute(){_result = _a + _b;}std::string ResultToString(){return std::to_string(_a) + " + " + std::to_string(_b) + " = " + std::to_string(_result);}std::string DebugToString(){return std::to_string(_a) + " + " + std::to_string(_b) + " = ?";}
private:int _a;int _b;int _result;
};

Main.cc

#include "BlockQueue.hpp"
#include "Thread.hpp"
#include "Task.hpp"
#include <string>
#include <vector>
#include <unistd.h>using namespace ThreadModule;
// 创建类型别名
using blockqueue_t = BlockQueue<Task>;// 消费者线程
void Consumer(blockqueue_t& bq)
{while (true){Task t;// 从阻塞队列中获取任务资源bq.Pop(&t);// 执行任务t.Execute();// 输出结果std::cout << "Consumer: " << t.ResultToString() << std::endl;}
}// 生产者线程
void Productor(blockqueue_t& bq)
{srand(time(nullptr)^pthread_self());while (true){// 分配任务int a = rand() % 10 + 1;usleep(1234);int b = rand() % 20 + 1;Task t(a, b);// 任务放入阻塞队列bq.Enqueue(t);// 输出任务信息std::cout << "Productor: " << t.DebugToString() << std::endl;sleep(1);}
}// 启动线程
void StartComm(std::vector<Thread<blockqueue_t>>* threads, int num, blockqueue_t& bq, func_t<blockqueue_t> func)
{for (int i = 0; i < num; i++){// 创建一批线程std::string name = "thread-" + std::to_string(i + 1);threads->emplace_back(func, bq, name);threads->back().Start();}
}// 创建消费者线程
void StartConsumer(std::vector<Thread<blockqueue_t>>* threads, int num, blockqueue_t& bq)
{StartComm(threads, num, bq, Consumer);
}// 创建生产者线程
void StartProductor(std::vector<Thread<blockqueue_t>>* threads, int num, blockqueue_t& bq)
{StartComm(threads, num, bq, Productor);
}// 等待所有线程结束
void WaitAllThread(std::vector<Thread<blockqueue_t>>& threads)
{for (auto& thread : threads){thread.Join();}
}int main()
{// 创建阻塞队列,容量为5blockqueue_t* bq = new blockqueue_t(5);// 创建线程std::vector<Thread<blockqueue_t>> threads;// 创建 1个消费者线程StartConsumer(&threads, 1, *bq);// 创建 1个生产者线程StartProductor(&threads, 1, *bq);// 等待所有线程结束WaitAllThread(threads);return 0;
}

结果演示

在这里插入图片描述
这里使用的是单生产者和单消费者,当然也可以在主函数处创建多生产者和多消费者的模型。


未完待续

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/46228.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

vue引入sm-crypto通过sm4对文件进行加解密,用户输入密码

对文件加密并保存&#xff1a; import { sm4 } from sm-cryptofetch("你的文件地址") .then(response > response.blob()) .then(byteStream > {const reader2 new FileReader();reader2.onload function(event) {const arrayBuffer event.target.result;l…

【Linux】Linux必备的基础指令

目录 Linux必备的基础指令一 、 什么是Linux二、 Linux常用命令2.1 ls2.2 pwd2.3 cd2.4 touch2.5 cat2.6 mkdir2.7 rm 三、 Linux重要指令3.1 cp3.2 mv3.3 tail3.4 vim3.5 grep3.6 ps3.7 netstat Linux必备的基础指令 一 、 什么是Linux 系统编程&⽹络编程 Linux⾃⾝提供…

快速掌握块级盒子垂直水平居中的几种方式

大家好&#xff01;今天我们来聊聊Web开发中如何实现块级盒子水平居中。在前端开发中&#xff0c;经常需要将一个块级盒子在父元素中进行垂直和水平居中对齐&#xff0c;本文将介绍几种常见且高效的实现方法。 一、子元素有固定宽高 第一种情况 子元素有固定宽高&#xff08;…

面向对象设计(OOD)实践:探索组合、聚合和关联

面向对象设计&#xff08;OOD&#xff09;不仅是一种编程范式&#xff0c;更是一种思考问题和设计解决方案的方式。在OOD中&#xff0c;关系是对象之间交互的核心。本文将通过具体例子&#xff0c;深入探讨组合&#xff08;Composition&#xff09;、聚合&#xff08;Aggregati…

编译x-Wrt 全过程

参考自;​​​​​​c编译教程 | All about X-Wrt 需要详细了解的小伙伴还请参看原文 ^-^ 概念&#xff1a; x-wrt&#xff08;基于openwrt深度定制的发行版本&#xff09; 编译系统: ubuntu22.04 注意&#xff1a; 特别注意的是&#xff0c;整个编译过程&#xff0c;都是用 …

java异常体系(清晰解释)

java异常体系分为错误和异常。 &#xff08;1&#xff09;错误就是error&#xff0c;是程序解决不了的&#xff0c;例如OOM内存溢出&#xff0c;JVM运行时数据区&#xff1a;方法区、堆、虚拟机栈、本地方法栈、程序计数器中只有程序计数器不会OOM。 &#xff08;2&#xff0…

linux 查看 io使用率iotop

$ sudo apt install iotop iotop iotop 命令-CSDN博客

JAVA-----String类补充

一、常用方法 1、常见String类的获取功能 length&#xff1a;获取字符串长度&#xff1b; charAt(int index)&#xff1a;获取指定索引位置的字符&#xff1b; indexOf(int ch)&#xff1a;返回指定字符在此字符串中第一次出现处的索引&#xff1b; substring(int start)&…

汽车的驱动力,是驱动汽车行驶的力吗?

一、地面对驱动轮的反作用力&#xff1f; 汽车发动机产生的转矩&#xff0c;经传动系传至驱动轮上。此时作用于驱动轮上的转矩Tt产生一个对地面的圆周力F0&#xff0c;地面对驱动轮的反作用力Ft(方向与F0相反)即是驱动汽车的外力&#xff0c;此外力称为汽车的驱动力。 即汽车…

求的一个最长的子字符串的长度,该子字符串中每个字符出现的次数都最少为 k(Java使用递归)

题目描述&#xff1a; 求的一个最长的子字符串的长度&#xff0c;该子字符串中每个字符出现的次数都最少为 k。 示例 &#xff1a; 示例 1&#xff1a; 输入&#xff1a;s "aaabb", k 3 输出&#xff1a;3 解释&#xff1a;最长子串为 "aaa" &#xff0c…

SunnyUI中uiSplitContainer的使用

在SunnyUI控件库中&#xff0c;UISplitContainer 是一个类似于Windows Forms中 SplitContainer 控件的组件&#xff0c;它允许你在一个容器内分割两个面板&#xff0c;通常一个作为主面板&#xff0c;另一个作为辅助面板。UISplitContainer 提供了更现代和美观的样式&#xff0…

知识图谱研究综述笔记

推荐导读&#xff1a;知识图谱Knowledge Graph Embeddings 论文标题:A Survey on Knowledge Graphs:Representation, Acquisition and Applications发表期刊:IEEE TRANSACTIONS ON NEURAL NETWORKS AND LEARNING SYSTEMS, 2021本文作者&#xff1a;Shaoxiong Ji, Shirui Pan, M…

Swiper轮播图实现

如上图&#xff0c;列表左右滚动轮播&#xff0c;用户鼠标移动到轮播区域&#xff0c;动画停止&#xff0c;鼠标移开轮播继续。 此例子实现技术框架是用的ReactCSS。 主要用的是css的transform和transition来实现左右切换动画效果。 React代码&#xff1a; import React, { us…

二叉树六道基本习题,你都会了吗?

Hello大家好呀&#xff0c;本博客目的在于记录暑假学习打卡&#xff0c;后续会整理成一个专栏&#xff0c;主要打算在暑假学习完数据结构&#xff0c;因此会发一些相关的数据结构实现的博客和一些刷的题&#xff0c;个人学习使用&#xff0c;也希望大家多多支持&#xff0c;有不…

手把手教你写UART(verilog)

最近工作用uart用的比较多&#xff0c;为了让自己更好的掌握这个协议&#xff0c;写了这篇文章&#xff0c;解读了uart程序的编写过程&#xff08;程序参考了米联客的教程&#xff09;。 最基础的概念 UART是用来让两个设备之间传输数据的协议&#xff0c;毕竟我不能直接给你一…

llama-recipes

文章目录 一、关于 llama-recipes二、入门1、先决条件PyTorch Nightlies 2、安装1、使用pip安装2、使用可选依赖项安装3、从源代码安装 3、得到 Meta Llama 模型模型转换为 Hugging Face 三、存储库组织1、recipes/2、src/ 贡献 一、关于 llama-recipes github : https://gith…

享元模式(大话设计模式)C/C++版本

享元模式 C #include <iostream> #include <string> #include <map> using namespace std;// 用户类 用户网站的客户账号&#xff0c;是"网站"类的外部状态 class User { private:string m_name;public:User(string name){m_name name;}std::st…

鸿蒙HarmonyOS应用开发为何选择ArkTS不是Java?

前言 随着智能设备的快速发展&#xff0c;操作系统的需求也变得越来越多样化。为了满足不同设备的需求&#xff0c;华为推出了鸿蒙HarmonyOS。 与传统的操作系统不同&#xff0c;HarmonyOS采用了一种新的开发语言——ArkTS。 但是&#xff0c;刚推出鸿蒙系统的时候&#xff0…

linux文件处理----把一个文件拼接到另一个文件后

cat file1 file2 >> combined_filefile1 file2会依次加到指定的文件后面 查看文件里有多少行&#xff1a;wc -l filename 搜索某个文件里面是否包含字符串&#xff1a; grep "search-content" filename

代码随想录第六十五天|KMC47 参加科学大会

题1&#xff1a; 指路&#xff1a;47. 参加科学大会&#xff08;第六期模拟笔试&#xff09; (kamacoder.com) 思路与代码&#xff1a; 普通版&#xff1a; #include<iostream> #include<vector> #include<climits> using namespace std;int main() {int…