1 Star 0 Fork 0

Miun11/Linux_learning

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
pthread.hpp 3.49 KB
一键复制 编辑 原始数据 按行查看 历史
Miun11 提交于 2026-05-05 16:46 +08:00 . 线程封装
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
// 命名空间
namespace Pthread_Wrap
{
class Pthread
{
int num = 1;
using func_t = std::function<void()>;
private:
void EnableRunning()
{
_isrunning = true;
}
void EnableDetach()
{
_isdetach = true;
}
// 不能用这种方式实现线程的回调函数,因为成员函数的第一个参数默认是this
// void* routine(void* args)
// {}
// 解决方案:static修饰routine函数
// 普通成员函数隐含this指针(实例化对象的地址),依赖对象调用
// static成员函数不属于对象,属于类本身
static void *routine(void *args)
{
// static 成员函数只能访问其他static成员,不能直接访问普通成员
// 访问普通成员需要依赖具体对象(this)
// 将this强转为对象的指针,依赖self访问
Pthread *self = static_cast<Pthread *>(args);
// 调用执行方法
self->EnableRunning();
self->_func();
return nullptr;
}
public:
Pthread(func_t func)
: _tid(0),
_ret(nullptr),
_isdetach(false),
_isrunning(false),
_func(func)
{
_name = "pthread-" + std::to_string(num++);
}
// 分离新线程
void Detach()
{
if (_isrunning && !_isdetach)
{
// 主动分离
pthread_detach(_tid);
EnableDetach();
std::cout << "新线程被分离!" << std::endl;
}
}
bool Start()
{
// 将实例化对象this作为参数给routine
int n = pthread_create(&_tid, nullptr, routine, this);
if (n != 0)
{
std::cerr << "creat failed!" << std::endl;
return false;
}
std::cout << "creat pthread " << _name << " success!" << std::endl;
return true;
}
bool Stop()
{
if (_isrunning && !_isdetach)
{
int n = pthread_cancel(_tid);
if (n != 0)
{
std::cerr << "detach failed!" << std::endl;
return false;
}
else
{
_isrunning = false;
_isdetach = true;
std::cout << "新线程被分离!" << std::endl;
return true;
}
}
return false;
}
bool Join()
{
if (_isrunning && !_isdetach)
{
pthread_join(_tid, &_ret);
std::cout << "Join success!" << std::endl;
return true;
}
std::cout << "pthread have detached, no Join!" << std::endl;
return false;
}
~Pthread()
{
Join();
}
private:
std::string _name; // 线程名字
pthread_t _tid; // 线程id
void *_ret; // 记录返回值
bool _isdetach; // 标记是否分离
bool _isrunning; // 标记线程是否运行
func_t _func; // 新线程要执行的函数
};
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/miun11/Linux_learning.git
git@gitee.com:miun11/Linux_learning.git
miun11
Linux_learning
Linux_learning
master

搜索帮助