news 2026/9/10 13:28:25

【Linux】使用C++对线程进行封装

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
【Linux】使用C++对线程进行封装

这里直接看代码就行:

第一个版本:

#pragma once #include <iostream> #include <functional> #include <pthread.h> namespace ThreadModule { static int gnumber = 1; using callback_t = std::function<void ()>;//重点 enum class TSTATUS//线程状态 { THREAD_NEW, THREAD_RUNNING, THREAD_STOP }; std::string StatusString(TSTATUS s) { switch (s) { case TSTATUS::THREAD_NEW: return "THREAD_NEW"; case TSTATUS::THREAD_RUNNING: return "THREAD_RUNNING"; case TSTATUS::THREAD_STOP: return "THREAD_STOP"; } return nullptr; } std::string isJoin(bool joinable) { return joinable ? "true" : "false"; } class Thread { private: void ToRuning() { _status = TSTATUS::THREAD_RUNNING; } void ToStop() { _status = TSTATUS::THREAD_STOP; } static void* ThreadRoutine(void* args)//static : 取消 this 指针对该函数的干扰 { Thread *self = static_cast<Thread*>(args); pthread_setname_np(self->_tid,self->_name.c_str());//设置线程名 self->_cb(); self->ToStop(); return nullptr; } public: Thread(callback_t cb) :_tid(-1),_status(TSTATUS::THREAD_NEW),_joinable(true),_cb(cb),_result(nullptr) { _name = "Thread_" + std::to_string(gnumber++); } ~Thread() {} bool Start() { int n = pthread_create(&_tid,nullptr,ThreadRoutine,this); if(n != 0) return false; ToRuning(); return true; } void Join() { if (_joinable) { int n = pthread_join(_tid, &_result); if (n != 0) { std::cerr << "join error: " << n << std::endl; return; } (void)_result; _status = TSTATUS::THREAD_STOP; } else { std::cerr << "error, thread join status : " << _joinable << std::endl; } } void Detach() { if(_status == TSTATUS::THREAD_RUNNING && _joinable) { pthread_detach(_tid); _joinable = false; } else std::cout << "detach " << _name << "failed" << std::endl; } void Stop() { } void Die() { if(_status == TSTATUS::THREAD_RUNNING) { pthread_cancel(_tid); _status = TSTATUS::THREAD_STOP; } } void PrintInfo() { std::cout << "thread name: " << _name << std::endl; std::cout << "thread _tid: " << _tid << std::endl; std::cout << "thread _status: " << StatusString(_status) << std::endl; std::cout << "thread _joinable: " << isJoin(_joinable) << std::endl; } private: std::string _name; pthread_t _tid; TSTATUS _status; bool _joinable; callback_t _cb;//用户自定义线程的执行函数 void* _result;//线程的退出信息 }; } // namespace ThreadModule

第二个版本:

#pragma once #include <iostream> #include <functional> #include <pthread.h> namespace ThreadModule { static int gnumber = 1; template<class T> using callback_t = std::function<void (T&)>;//重点 enum class TSTATUS//线程状态 { THREAD_NEW, THREAD_RUNNING, THREAD_STOP }; std::string StatusString(TSTATUS s) { switch (s) { case TSTATUS::THREAD_NEW: return "THREAD_NEW"; case TSTATUS::THREAD_RUNNING: return "THREAD_RUNNING"; case TSTATUS::THREAD_STOP: return "THREAD_STOP"; } return nullptr; } std::string isJoin(bool joinable) { return joinable ? "true" : "false"; } template<class T> class Thread { private: void ToRuning() { _status = TSTATUS::THREAD_RUNNING; } void ToStop() { _status = TSTATUS::THREAD_STOP; } static void* ThreadRoutine(void* args)//static : 取消 this 指针对该函数的干扰 { Thread<T> *self = static_cast<Thread<T>*>(args); pthread_setname_np(self->_tid,self->_name.c_str());//设置线程名 self->_cb(self->_data); self->ToStop(); return nullptr; } public: Thread(callback_t<T> cb,const T& data) :_tid(-1) ,_status(TSTATUS::THREAD_NEW) ,_joinable(true),_cb(cb) ,_result(nullptr) ,_data(data) { _name = "Thread_" + std::to_string(gnumber++); } ~Thread() {} bool Start() { int n = pthread_create(&_tid,nullptr,ThreadRoutine,this); if(n != 0) return false; ToRuning(); return true; } void Join() { if (_joinable) { int n = pthread_join(_tid, &_result); if (n != 0) { std::cerr << "join error: " << n << std::endl; return; } (void)_result; _status = TSTATUS::THREAD_STOP; } else { std::cerr << "error, thread join status : " << _joinable << std::endl; } } void Detach() { if(_status == TSTATUS::THREAD_RUNNING && _joinable) { pthread_detach(_tid); _joinable = false; } else std::cout << "detach " << _name << "failed" << std::endl; } void Stop() { } void Die() { if(_status == TSTATUS::THREAD_RUNNING) { pthread_cancel(_tid); _status = TSTATUS::THREAD_STOP; } } void PrintInfo() { std::cout << "thread name: " << _name << std::endl; std::cout << "thread _tid: " << _tid << std::endl; std::cout << "thread _status: " << StatusString(_status) << std::endl; std::cout << "thread _joinable: " << isJoin(_joinable) << std::endl; } private: std::string _name; pthread_t _tid; TSTATUS _status; bool _joinable; callback_t<T> _cb;//用户自定义线程的执行函数 void* _result;//线程的退出信息 T _data; }; } // namespace ThreadModule

测试封装的线程:

#include "Thread_version1.hpp" #include <unistd.h> #include <vector> class Task { public: Task(int x, int y) : _x(x), _y(y) { } void Execute() { _result = _x + _y; } void Print() { std::cout << _x << "+" << _y << "=" << _result << std::endl; } private: int _x; int _y; int _result; }; // void routine(int cnt) // { // char name[64]; // pthread_getname_np(pthread_self(),name,sizeof(name)); // int cnt = 10; // while(true) // { // std::cout << "new thread running: " << name << "count :" << std::endl; // sleep(1); // } // } int main() { //构建任务 srand(time(nullptr) ^ getpid()); const int num = 10; std::vector<Task> tasks; for(int i = 0; i < 10;i++) { tasks.emplace_back(rand()%10 + 1,3); } std::vector<ThreadModule::Thread> threads; for(int i = 0;i < 10;i++) { threads.emplace_back([i,&tasks](){ tasks[i].Execute(); }); } for(auto& t : threads) { t.Start(); } for(auto& t : threads) { t.Join(); t.PrintInfo(); } for(auto& t : tasks) { t.Print(); } //////////////////////////////////////////////////// // ThreadModule::Thread<int> t(routine,10);//关于可以传多个参数问题,可以传个类过去,这个类里面有多个类型变量 // sleep(1); // t.Start();//创建线程 // sleep(5); // t.Die();//杀掉线程 // sleep(1); // t.Join();//等待线程 // t.PrintInfo();//打印线程信息 return 0; }
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/3 3:19:23

(C#内联数组真实性能报告)基于.NET 8的10组压力测试结果曝光

第一章&#xff1a;C#内联数组性能测试概述在高性能计算和低延迟应用场景中&#xff0c;C# 的内存管理机制对程序执行效率具有显著影响。内联数组&#xff08;Inline Arrays&#xff09;作为 .NET 7 引入的一项重要语言特性&#xff0c;允许开发者在结构体中声明固定长度的数组…

作者头像 李华
网站建设 2026/9/6 14:53:55

【实战】企业级物联网架构-元数据与物模型

本篇梳理了元数据和物模型在企业级应用架构中的核心作用。通过元数据实现业务定义的灵活配置&#xff0c;通过物模型实现设备与业务解耦&#xff0c;为系统的高可扩展性、标准化和低耦合提供基础参考&#xff0c;并配套示例辅助理解结构。 请关注公众号【碳硅化合物AI】 在企业…

作者头像 李华
网站建设 2026/9/10 3:28:19

吐血推荐10个AI论文工具,专科生搞定毕业论文+格式规范!

吐血推荐10个AI论文工具&#xff0c;专科生搞定毕业论文格式规范&#xff01; AI 工具&#xff0c;让论文写作不再难 对于专科生来说&#xff0c;毕业论文不仅是学业的终点&#xff0c;也是能力的一次全面检验。然而&#xff0c;面对繁重的写作任务、复杂的格式规范以及不断变化…

作者头像 李华
网站建设 2026/9/7 12:27:56

C# 12拦截器性能优化秘诀:3种高效拦截方法调用的实践方案

第一章&#xff1a;C# 12拦截器概述与核心价值C# 12 引入的拦截器&#xff08;Interceptors&#xff09;是一项实验性语言特性&#xff0c;旨在允许开发者在编译期将函数调用动态替换为其他实现。这一机制特别适用于提升代码性能、简化测试逻辑以及增强诊断能力&#xff0c;而无…

作者头像 李华
网站建设 2026/9/7 3:41:39

析构和构造的顺序:成员对象、全局对象、局部对象

在 C 中&#xff0c;成员对象、全局对象、局部对象 的生命周期和执行时机是内存管理的核心知识点&#xff0c;其规则由 C 标准严格定义&#xff0c;下面分模块详细拆解&#xff0c;结合示例说明关键细节。一、成员对象的生命周期成员对象是指作为类 / 结构体成员的对象&#xf…

作者头像 李华