当前位置: 首页 > backend >正文

线程封装

目录

makefile

Thread.hpp

main.cc


以面向对象的方式造轮子

#ifndef _THREAD_HPP__  // 如果没有定义过 _THREAD_HPP__
#define _THREAD_HPP__  // 则定义 _THREAD_HPP__// 这里是头文件的实际内容(类、函数声明等)#endif                // 结束条件编译

makefile

bin=testThread
cc=g++
src=$(wildcard *.cc)
obj=$(src:.cc=.o)$(bin):$(obj)$(cc) -o $@ $^ -lpthread
%.o:%.cc$(cc) -c $< -std=c++17.PHONY:clean
clean:rm -f $(bin) $(obj)

Thread.hpp

#ifndef _THREAD_HPP__  // 如果没有定义过 _THREAD_HPP__
#define _THREAD_HPP__  // 则定义 _THREAD_HPP__
#include<iostream>
#include<string>
#include<pthread.h>
#include<functional>
#include <sys/types.h>
#include <unistd.h>namespace ThreadModule
{
using func_t =std::function<void()>;
static int number = 1;
enum class STATUS
{NEW,RUNNING,STOP};class Thread 
{// void* Route(void* args)   成员函数参数里有this指针 ,start(Route ,nullptr)编不过// {// }static void *Route(void* args)   //static没有传进来this指针 ,也就不能使用成员变量    _name 等等{Thread* t =static_cast< Thread* >(args);t->_status =STATUS::RUNNING;t->_func();return nullptr;}void EnableDetach(){_joinable =false;}public:Thread(func_t func) :_func(func),_status(STATUS::NEW),_joinable(true){_name ="Thread-"+std::to_string(number++);_pid =getpid();}bool Start(){if(_status != STATUS::RUNNING)//防止重复启动{int n =::pthread_create(&_tid ,nullptr, Route ,this );if(n !=0) return false;_status = STATUS::RUNNING;return true;}return false;}bool Stop(){if(_status == STATUS::RUNNING){int n= pthread_cancel(_tid);if(n!= 0) return false;_status = STATUS::STOP;return true;}return false;}void Detach(){EnableDetach();pthread_detach(_tid);}bool isjoinable(){return _joinable;}bool Join(){if( _joinable){int n =pthread_join(_tid ,nullptr);if(n != 0)return false;_status =STATUS::STOP;return true;}return false;}std::string Name(){return _name;}~Thread(){}
private:std::string _name;pthread_t _tid;pid_t _pid;STATUS _status;    //线程结束(stop了)不代表Thread对象结束,因此应该设计线程状态bool _joinable ;//是否分离 ,默认不是分离状态, truefunc_t _func;
};} #endif                // 结束条件编译

main.cc

#include"Thread.hpp"
#include<unordered_map>
#include<memory>#define NUM 10using thread_ptr_t = std::shared_ptr<ThreadModule::Thread>;//创建多线程
int main()
{// 先描述,在组织!std::unordered_map<std::string, thread_ptr_t> threads;// 如果我要创建多线程呢???for (int i = 0; i < NUM; i++){thread_ptr_t t = std::make_shared<ThreadModule::Thread>([](){while(true){std::cout << "hello world" << std::endl;sleep(1);}});threads[t->Name()] = t;}for(auto &thread:threads){thread.second->Start();}for(auto &thread:threads){thread.second->Join();}return 0;
}//创建线程
// int main()
// {
//     ThreadModule::Thread t([](){//         while(true)
//         {
//             std::cout<<"hello "<<std::endl;
//             sleep(1);
//         }
//     });
//     t.Start();
//     std::cout<<t.Name()<<"is running"<<std::endl;//     sleep(5);
//     t.Stop();
//     std::cout << "Stop thread : " << t.Name()<< std::endl;//     sleep(1);
//     t.Join();
//     std::cout << "Join thread : " << t.Name()<< std::endl;//     return 0;
// }

http://www.xdnf.cn/news/1364.html

相关文章:

  • Pytorch图像数据转为Tensor张量
  • 初识Redis · 事务
  • HTTP:十一.HTTP认证概述
  • 12-DevOps-Gitlab托管Jenkinsfile
  • 使用 Conda 创建新环境
  • 关于Agent的简单构建和分享
  • 卷积神经网络(CNN)详细教程
  • LSTM-GAN生成数据技术
  • 计组1.2.3——计算机软件
  • 第十五届蓝桥杯 2024 C/C++组 合法密码
  • 《巧用DeepSeek快速搞定数据分析》书籍分享
  • 知识储备-DC综合相关
  • 大厂面试:MySQL篇
  • 深度剖析塔能科技精准节能方案:技术创新与实践价值
  • ShenNiusModularity项目源码学习(20:ShenNius.Admin.Mvc项目分析-5)
  • Git 远程操作全攻略:从基础到实战
  • jmeter中监控服务器ServerAgent
  • 华为开发岗暑期实习笔试(2025年4月16日)
  • 新品发布 | 6 秒全谱成像,VIX-N320 内置推扫式高光谱相机重磅发布
  • crictl 遇到报错 /run/containerd/containerd.sock: connect: permission denied
  • 设计模式--工厂模式详解
  • 【Docker】在Ubuntu平台上的安装部署
  • AIGC的爆发:哪些行业将被彻底颠覆?
  • Arduino示例代码讲解: Project 12 - Knock Lock 锁
  • # 06_Elastic Stack 从入门到实践(六)
  • 【MySQL】(7) 数据库设计
  • 【集合】底层原理实现及各集合之间的区别
  • 数据库操作
  • 遥感生物多样性产品
  • 【LLM】Ollama:容器化并加载本地 GGUF 模型