适配qnx和linux平台的线程管理类封装
概述
封装代码仓库: https://gitee.com/liudegui/my_thread
尝试封装一个基于C++11的多线程控制与调度类,适配QNX和Linux平台,且代码符合Misra标准。它提供了以下主要功能:
- 线程的创建与销毁管理。
- 线程的优先级调度。
- 线程的CPU亲和性设置。
- 线程的等待与唤醒机制。
类的结构及主要成员函数如下:
- 构造函数与析构函数:负责初始化线程相关参数,并在析构时确保线程安全退出。
- thread_start():启动线程,创建指定数量的线程实例。
- thread_shutdown():关闭线程,释放资源并等待所有线程退出。
- timed_wait():线程的超时等待机制,防止线程无限等待。
- set_self_thread_priority():设置当前线程的优先级。
实现细节
MyThread类内部实现主要涉及以下几个方面:
- 使用std::thread来创建线程实例。
- 利用std::mutex和std::condition_variable来实现线程同步。
- 使用pthread库来设置线程的优先级和CPU亲和性。
/**
* my_thread.h
*/#ifndef UTILS_MY_THREAD_H_
#define UTILS_MY_THREAD_H_#include <atomic>
#include <cstdint>
#include <functional>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include <condition_variable>
#include <memory>namespace MyTest {
class MyThread {public:explicit MyThread(const std::string& in_name, int32_t in_priority, uint32_t in_worker_num,const std::function<void()> in_func, int32_t in_cpusetsize, const cpu_set_t*const in_cpuset);~MyThread();void thread_start();void thread_shutdown();bool has_shutdown() const {return is_shutdown_;}void timed_wait(uint32_t useconds);static void set_self_thread_priority(int32_t in_priority);private:static void my_thread_func_(MyThread* thread_ins);private:std::string thread_name_;int32_t thread_priority_;uint32_t thread_worker_num_;std::vector<std::shared_ptr<std::thread>> my_threads_;std::function<void()> func_main_;int32_t thread_cpusetsize_;const cpu_set_t* thread_cpuset_ = nullptr;std::mutex thread_mutex_;std::condition_variable thread_cond_;bool is_shutdown_;
};} // namespace MyTest#endif // UTILS_MY_THREAD_H_
/**
* my_thread.cpp
*/#include "my_thread.h"#include <ctime>
#include <sstream>
#ifndef _QNX_
#include <sys/syscall.h>
#endif
#include <sys/types.h>
#include "fake_log.h"namespace MyTest {MyThread::MyThread(const std::string& in_name, int32_t in_priority, uint32_t in_worker_num,const std::function<void()> in_func, int32_t in_cpusetsize, const cpu_set_t* const in_cpuset): thread_name_(in_name),thread_priority_(in_priority),thread_worker_num_(in_worker_num),func_main_(in_func),thread_cpusetsize_(in_cpusetsize),thread_cpuset_(in_cpuset),is_shutdown_(true) {
}MyThread::~MyThread() {if (!is_shutdown_) {thread_shutdown();}
}void MyThread::my_thread_func_(MyThread* thread_ins) {if (thread_ins == nullptr) {MY_LOG_ERROR("thread_ins is nullptr");} else {
#ifndef _QNX_if ((thread_ins->thread_cpuset_ != nullptr) && (thread_ins->thread_cpusetsize_ > 0)) {const pthread_t tid = pthread_self();const auto np_return =pthread_setaffinity_np(tid, static_cast<size_t>(thread_ins->thread_cpusetsize_), thread_ins->thread_cpuset_);if (np_return != 0) {MY_LOG_ERROR("pthread_setaffinity_np failed. return=%d", np_return);}}
#else// qnx ...
#endifstd::stringstream thread_id_stream;thread_id_stream << std::this_thread::get_id();MY_LOG_INFO("thread %s starts. pid=%s target_priority=%d", thread_ins->thread_name_.c_str(),thread_id_stream.str().c_str(), thread_ins->thread_priority_);MyThread::set_self_thread_priority(thread_ins->thread_priority_);try {thread_ins->func_main_();} catch (...) {MY_LOG_ERROR("Exception occurred in thread %s", thread_ins->thread_name_.c_str());}}
}void MyThread::thread_start() {std::lock_guard<std::mutex> lck(thread_mutex_);is_shutdown_ = false;my_threads_.resize(thread_worker_num_);uint32_t thread_idx = 0;for (; thread_idx < thread_worker_num_; thread_idx++) {my_threads_[thread_idx] = std::make_shared<std::thread>(my_thread_func_, this);}
}void MyThread::thread_shutdown() {std::lock_guard<std::mutex> lck(thread_mutex_);if (!is_shutdown_) {is_shutdown_ = true;thread_cond_.notify_all();for (const auto& my_t : my_threads_) {if (my_t->joinable()) {my_t->join();}}}
}void MyThread::timed_wait(uint32_t useconds) {std::unique_lock<std::mutex> lck(thread_mutex_);const auto timeout_val = std::chrono::microseconds(useconds);do {const auto return_val = thread_cond_.wait_for(lck, timeout_val);if (return_val == std::cv_status::timeout) {MY_LOG_ERROR("thread timed_wait timeout");}} while (false);
}void MyThread::set_self_thread_priority(int32_t in_priority) {bool go_on = true;struct sched_param params;struct sched_param current_params;int32_t set_policy{0};int32_t current_policy{0};const pthread_t this_thread = pthread_self();int32_t status_ret = pthread_getschedparam(this_thread, ¤t_policy, ¤t_params);if (status_ret != 0) {MY_LOG_ERROR("getschedparam %d", status_ret);go_on = false;} else {MY_LOG_DEBUG("thread current priority is %d (%d), target is %d", current_params.sched_priority, current_policy,in_priority); // MY_LOG_TRACEif (in_priority == 0) {go_on = false;} else if (in_priority > 0) {set_policy = SCHED_FIFO;params.sched_priority = current_params.sched_priority + in_priority;} else {set_policy = SCHED_IDLE;params.sched_priority = 0;}}if (go_on) {if (params.sched_priority > 99) {params.sched_priority = 99;}if (params.sched_priority < 0) {params.sched_priority = 0;}status_ret = pthread_setschedparam(this_thread, set_policy, ¶ms);if (status_ret != 0) {MY_LOG_WARN("setschedparam(%d)", params.sched_priority);go_on = false;}}if (go_on) {status_ret = pthread_getschedparam(this_thread, ¤t_policy, ¤t_params);if (status_ret != 0) {MY_LOG_ERROR("getschedparam 2 %d", status_ret);} else {if (current_params.sched_priority != params.sched_priority) {MY_LOG_ERROR("current priority=%d (%d), target is %d", current_params.sched_priority, current_policy,params.sched_priority);} else {MY_LOG_INFO("set thread priority to %d (%d)", current_params.sched_priority, current_policy);}}}
}} // namespace MyTest
测试代码
#include "my_thread.h"#include <chrono>
#include <iostream>
#include <string>namespace MyTest {
static void worker_function() {std::this_thread::sleep_for(std::chrono::milliseconds(100));std::cout << "Thread ID: " << std::this_thread::get_id() << " is working." << std::endl;
}
} // namespace MyTestint32_t main() {int32_t main_res{0};try {const uint32_t num_threads = 4;cpu_set_t cpuset1;CPU_ZERO(&cpuset1);CPU_SET(0, &cpuset1);std::vector<std::shared_ptr<MyTest::MyThread>> test_threads;uint32_t thread_idx = 0;for (; thread_idx < num_threads; ++thread_idx) {const std::string thread_name1 = std::string("Thread_") + std::to_string(thread_idx);const std::shared_ptr<MyTest::MyThread> my_t = std::make_shared<MyTest::MyThread>(thread_name1, 1, 1, MyTest::worker_function, sizeof(cpuset1), &cpuset1);test_threads.push_back(my_t);}for (const auto& my_t : test_threads) {my_t->thread_start();}std::this_thread::sleep_for(std::chrono::seconds(2));for (const auto& my_t : test_threads) {my_t->thread_shutdown();}for (const auto& my_t : test_threads) {while (!my_t->has_shutdown()) {// std::this_thread::yield();my_t->timed_wait(100);}}std::cout << "All threads have been shutdown." << std::endl;} catch (...) {std::cerr << "Exception occurred" << std::endl;main_res = 1;}return main_res;
}
相关文章:
适配qnx和linux平台的线程管理类封装
概述 封装代码仓库: https://gitee.com/liudegui/my_thread 尝试封装一个基于C11的多线程控制与调度类,适配QNX和Linux平台,且代码符合Misra标准。它提供了以下主要功能: 线程的创建与销毁管理。线程的优先级调度。线程的CPU亲…...
【信息系统项目管理师】复习~第十五章
15.项目风险管理 每个项目都存在两个层面上的风险:①每个项目都有会影响项目达成目标的单个风险;②由单个风险和不确定性的其他来源联合导致的整体项目风险。项目风险会对项目目标产生负面或正面的影响,也就是风险与机会。项目风险管理旨在利…...
ARM单片机实现流水灯(GD32)
根据上图可知使用的引脚分别是PA8,PE6,PF6流水灯功能的实现要分别初始化这几个引脚 流水灯实现 编写流水灯代码 LED.C #include "gd32f30x.h" // Device header #include "Delay.h" // 初始化LED灯 void LED_Init(void){// 使能RCU时钟…...
操作系统基础之磁盘
概述 基本概念 磁盘有正反两个盘面,每个盘面有多个同心圆,每个同心圆是一个磁道,每个同心圆又被划分为多个扇区,数据就被存在扇区中。 磁头首先寻找到对应磁道,然后等到磁盘进行周期旋转到指定的扇区,才…...
【Unity Shader入门精要 第6章】基础光照(一)
1. 什么是光照模型 光照原理 在真实世界中,我们能够看到物体,是由于眼睛接收到了来自观察目标的光。这里面包括两种情况:一部分是观察目标本身发出的光(自发光)直接进入我们的眼睛,另一部分是其他物体&am…...
JavaEE概述 + Maven
文章目录 一、JavaEE 概述二、工具 --- Maven2.1 Maven功能 仓库 坐标2.2 Maven之项目构建2.3 Maven之依赖管理 三、插件 --- Maven Helper 一、JavaEE 概述 Java SE、JavaEE: Java SE:指Java标准版,适用于各行各业,主要是Java…...
python把png转成jpg
在Python中,你可以使用PIL(Python Imaging Library,也称为Pillow)库来读取PNG图片并将其转换为JPG格式。下面是一个简单的示例代码: from PIL import Image# 打开PNG图片 png_image Image.open(input.png)# 保存为JP…...
信息系统架构基本概念及发展_2.信息系统架构的定义
1.几种架构的定义 信息系统架构仍在不断发展中,还没有形成一个公认的定义,这里举出几个定义。 定义1:软件或计算机系统的信息系统架构是该系统的一个(或多个)结构,而结构由软件元素、元素的外部可见…...
ctfshow SSRF 351-358
做题前,需要先学习关于ssrf漏洞的相关知识 小注意: 当使用 file_get_contents() 函数访问远程 URL 时,它会尝试获取该 URL 指向的资源的内容,并将内容以字符串的形式返回。 如果 b.php 文件是一个 PHP 文件,它包含的内容取决于该 PHP 文件…...
优化学习方法,事半功倍
学习,是人一生中必不可少的过程。在学习的道路上,我们会遇到各种各样的挑战和困难,但只要我们能够发现并优化适合自己的学习方法,就能事半功倍,取得更好的成绩。 首先,要充分了解自己的学习方式和习惯。每个…...
Spring STOMP-开启STOMP
通过Spring框架的spring-messaging和spring-websocket模块,提供了对WebSocket上STOMP的支持。一但你添加了这些依赖项,你就可以像下面这个示例一样,通过WebSocket公开一个STOMP端点: import org.springframework.web.socket.conf…...
Python 开发 框架安全:Django SQL注入漏洞测试.(CVE-2021-35042)
什么是 Django 框架 Django 是一个用 Python 编写的 Web 应用程序框架。它提供了许多工具和库,使得开发 Web 应用程序变得更加容易和高效。Django 遵循了“MTV”(模型-模板-视图)的设计模式,将应用程序的不同组件分离开来&#x…...
《Python编程从入门到实践》day25
# 昨日知识点回顾 如何创建多行外星人 碰撞结束游戏 创建game_stats.py跟踪统计信息 # 今日知识点学习 第14章 记分 14.1 添加Play按钮 14.1.1 创建Button类 import pygame.font# button.py class Button:def __init__(self, ai_game, msg):"""初始化按钮…...
Unity 性能优化之光照优化(七)
提示:仅供参考,有误之处,麻烦大佬指出,不胜感激! 文章目录 前言一、测试目的一、实时光源是什么?二、开始测试1.场景中只有一个光照的数值情况2.添加4个点光源后4.结果 总结 前言 实时光源数量越多&#x…...
C语言 | Leetcode C语言题解之第84题柱状图中最大的矩形
题目: 题解: int largestRectangleArea(int* heights, int heightsSize) {int st[heightsSize];int p[2];p[0]-1,p[1]heightsSize;int size0,result0;st[size]0;for(int i1;i<heightsSize;i){ while(size!0&&heights[i]<heights[st[size-1…...
AI办公自动化-用kimi批量重命名Word文档
文件夹里面有很多个word文档,标题里面都含有零代码编程,现在想将其替换为AI办公自动化。 在kimichat中输入提示词: 你是一个Python编程专家,要完成一个编写Python脚本的任务,具体步骤如下: 打开文件夹&am…...
Golang 并发 Mutex 互斥锁的使用
Golang 并发 Mutex 互斥锁的使用 1. 初始化 func TestMutex(t *testing.T) {mu01 : sync.Mutex{}var mu02 sync.Mutex }两种方式都ok 2. Mutex使用 计数器统计,多个协程同时对同一个变量进行 代码示例 var mu sync.Mutex var counter intfunc TestMutexAdd(t…...
20232906 2023-2024-2 《网络与系统攻防技术》第九次作业
20232906 2023-2024-2 《网络与系统攻防技术》第九次作业 1.实验内容 本次实践的对象是一个名为pwn1的linux可执行文件。 该程序正常执行流程是:main调用foo函数,foo函数会简单回显任何用户输入的字符串。 该程序同时包含另一个代码片段,getShell&am…...
常见的十二种软件架构
常用的软件架构有多种,以下是一些主要的软件架构风格: 单体架构(Monolithic Architecture): 描述:所有功能都集中在一个应用或系统中,易于开发和部署,但随着系统增长,可能…...
数据库出现死锁的解决方法参考
死锁引起的原因一般是多个用户并发访问数据库导致的问题,或是因为某个进程挂死以后资源未释放导致的。通过onstat –p可查看deadlks项大于0即表示历史总计死锁次数。对于被锁的表进行操作的时候会出现-143 ISAM error: deadlock detected的错误。当其他会话访问此表…...
【位运算】消失的两个数字(hard)
消失的两个数字(hard) 题⽬描述:解法(位运算):Java 算法代码:更简便代码 题⽬链接:⾯试题 17.19. 消失的两个数字 题⽬描述: 给定⼀个数组,包含从 1 到 N 所有…...
鸿蒙中用HarmonyOS SDK应用服务 HarmonyOS5开发一个生活电费的缴纳和查询小程序
一、项目初始化与配置 1. 创建项目 ohpm init harmony/utility-payment-app 2. 配置权限 // module.json5 {"requestPermissions": [{"name": "ohos.permission.INTERNET"},{"name": "ohos.permission.GET_NETWORK_INFO"…...
【C语言练习】080. 使用C语言实现简单的数据库操作
080. 使用C语言实现简单的数据库操作 080. 使用C语言实现简单的数据库操作使用原生APIODBC接口第三方库ORM框架文件模拟1. 安装SQLite2. 示例代码:使用SQLite创建数据库、表和插入数据3. 编译和运行4. 示例运行输出:5. 注意事项6. 总结080. 使用C语言实现简单的数据库操作 在…...
鱼香ros docker配置镜像报错:https://registry-1.docker.io/v2/
使用鱼香ros一件安装docker时的https://registry-1.docker.io/v2/问题 一键安装指令 wget http://fishros.com/install -O fishros && . fishros出现问题:docker pull 失败 网络不同,需要使用镜像源 按照如下步骤操作 sudo vi /etc/docker/dae…...
技术栈RabbitMq的介绍和使用
目录 1. 什么是消息队列?2. 消息队列的优点3. RabbitMQ 消息队列概述4. RabbitMQ 安装5. Exchange 四种类型5.1 direct 精准匹配5.2 fanout 广播5.3 topic 正则匹配 6. RabbitMQ 队列模式6.1 简单队列模式6.2 工作队列模式6.3 发布/订阅模式6.4 路由模式6.5 主题模式…...
人工智能 - 在Dify、Coze、n8n、FastGPT和RAGFlow之间做出技术选型
在Dify、Coze、n8n、FastGPT和RAGFlow之间做出技术选型。这些平台各有侧重,适用场景差异显著。下面我将从核心功能定位、典型应用场景、真实体验痛点、选型决策关键点进行拆解,并提供具体场景下的推荐方案。 一、核心功能定位速览 平台核心定位技术栈亮…...
32单片机——基本定时器
STM32F103有众多的定时器,其中包括2个基本定时器(TIM6和TIM7)、4个通用定时器(TIM2~TIM5)、2个高级控制定时器(TIM1和TIM8),这些定时器彼此完全独立,不共享任何资源 1、定…...
flow_controllers
关键点: 流控制器类型: 同步(Sync):发布操作会阻塞,直到数据被确认发送。异步(Async):发布操作非阻塞,数据发送由后台线程处理。纯同步(PureSync…...
STM32标准库-ADC数模转换器
文章目录 一、ADC1.1简介1. 2逐次逼近型ADC1.3ADC框图1.4ADC基本结构1.4.1 信号 “上车点”:输入模块(GPIO、温度、V_REFINT)1.4.2 信号 “调度站”:多路开关1.4.3 信号 “加工厂”:ADC 转换器(规则组 注入…...
Heygem50系显卡合成的视频声音杂音模糊解决方案
如果你在使用50系显卡有杂音的情况,可能还是官方适配问题,可以使用以下方案进行解决: 方案一:剪映替换音色(简单适合普通玩家) 使用剪映换音色即可,口型还是对上的,没有剪映vip的&…...
