线程封装
目录
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;
// }