🌏博客主页:PH_modest的博客主页
🚩当前专栏:Linux跬步积累
💌其他专栏:
🔴 每日一题
🟡 C++跬步积累
🟢 C语言跬步积累
🌈座右铭:广积粮,缓称王!
文章目录
一、如何实现一个线程
1、基本结构
Thread类是用来描述一个线程的,所以成员变量中需要有tid和线程名。所以第一个成员变量就是==_tid==;
一个线程创建出来,肯定是用来执行对于的任务的,那么我们还需要一个成员变量来接收传递的函数,所以第三个成员变量就是==_func==,是一个void(T&)类型的参数,所以第四个成员变量就是传递过来的参数_data。
template<class T>
using func_t = std::function<void(T&)>;//模版方法
template<class T>
class Thread
{
public:
Thread(){
}
static void* ThreadRoutinue(){
}
void Start(){
}
void Join(){
}
void Detach(){
}
~Thread(){
}
private:
pthread_t _tid; //线程tid
std::string _threadname; //线程名
func_t<T> _func; //线程执行的函数
T _data; //需要处理的数据
};
2、实现成员函数
成员函数中我们需要注意的就是
pthread_create()
函数,它的第三个参数是一个参数为void *,返回值为void *的一个函数。但是我们将这个函数
ThreadRoutinue()
定义在这个类里,他就是一个成员函数,成员函数的参数,会隐藏this指针,所以如果我们正常写,就会报错,因为这个函数不满足pthread_create()
函数的条件。但是只要让
ThreadRoutinue()
的参数中没有this指针就可以了,那么该如何实现呢?在前面加上static就可以,变成静态成员变量,就不会有this指针了。那么问题又来了,没有了this指针,我们又该如何访问到成员变量呢?
别忘了这个函数可以传递一个返回值为void*的参数,我们只需要将this指针传递过去,在函数内部强转一下就可以了。
template<class T>
using func_t = std::function<void(T&)>;//模版方法
template<class T>
class Thread
{
public:
//thread(func,5,"thread-1");
Thread(func_t<T> func,const T &data,const std::string &name = "none-name")
:_func(func),_data(data),_threadname(name)
{
}
//需要设置成static静态成员函数,否则参数会多一个this指针,就不符合pthread_create的要求了
static void* ThreadRoutinue(void* args)
{
//将传过来的this指针强转一下,然后就可以访问到_func和_data了
Thread<T>* self = static_cast<Thread<T>*>(args);
self->_func(self->_data);
return nullptr;
}
void Start()
{
//创建线程
int ret = pthread_create(&_tid,nullptr,ThreadRoutinue,this);
return ret==0;
}
void Join()
{
pthread_join(_tid,nullptr);
}
void Detach()
{
pthread_detach(_tid);
}
~Thread(){
}
private:
pthread_t _tid; //线程tid
std::string _threadname; //线程名
func_t<T> _func; //线程执行的函数
T _data; //需要处理的数据
};
3、演示
让我们写一段测试代码,来看一下效果:
#include"Thread.hpp"
void test(int x)
{
while(true)
{
std::cout<<x<<std::endl;
sleep(1);
}
}
int main()
{
MyThread::Thread<int> mt(test,2025,"thread-1");
if(mt.Start() == true)
{
std::cout<<"MyThread start success!\n";
}
else
{
std::cout<<"MyThread start failed!\n";
}
mt.Join();
return 0;
}
运行结果:
让我们使用ps -aL
指令来查看一下是否真的创建了线程:
可以看到,程序运行之后,真的创建出了两个名为mythread的线程。
4、代码总汇
Thread.hpp
#pragma once
#include<string>
#include<pthread.h>
#include<unistd.h>
#incl