定义业务类,继承 Thread类,实现run函数。可跨平台,调用start()即可
#pragma once
#include <thread>
#include <atomic>
#include <functional>
class Thread
{
private:
std::thread _thread; // std::thread 对象
std::atomic<bool> _isRunning; // 原子标志:线程是否在运行
std::atomic<bool> _stopRequested; // 原子标志:是否请求停止
protected:
/**
* 子类必须重写此函数,实现线程的业务逻辑
* 在 run() 中应定期检查 isStopRequested() 来响应停止请求
*/
virtual void run() = 0;
/**
* 线程入口函数(非虚,避免在构造/析构期间调用虚函数)
*/
void threadEntry()
{
if (_isRunning.exchange(true)) {
return; // 防止重复执行
}
run(); // 调用业务逻辑
_isRunning.store(false);
}
public:
// 禁止拷贝(thread 不可拷贝)
Thread(const Thread&) = delete;
Thread& operator=(const Thread&) = delete;
/**
* 构造函数
*/
Thread()
: _isRunning(false)
, _stopRequested(false)
{
}
/**
* 析构函数
* 自动等待线程结束(join),确保资源安全释放
* 建议:显式调用 join() 或 stop(),避免在析构时阻塞
*/
virtual ~Thread()
{
if (_thread.joinable()) {
// 如果线程仍在运行,尝试请求停止并等待
if (_isRunning.load()) {
requestStop();
}
_thread.join(); // 等待线程安全退出
}
}
/**
* 启动线程
* @return 成功启动返回 true
*/
bool start()
{
if (_thread.joinable() || _isRunning.load()) {
return false; // 已启动或线程对象仍可连接
}
try {
_thread = std::thread(&Thread::threadEntry, this);
return true;
} catch (...) {
return false; // std::thread 构造可能抛出异常(如资源不足)
}
}
/**
* 等待线程结束
*/
void join()
{
if (_thread.joinable()) {
_thread.join();
}
}
/**
* 分离线程(detach)
* 线程将在后台运行,结束后自动释放资源
* 注意:分离的线程无法 join,需自行管理生命周期
*/
void detach()
{
if (_thread.joinable()) {
_thread.detach();
}
}
/**
* 请求线程停止(协作式终止)
* 子类应在 run() 中定期调用 isStopRequested() 并优雅退出
*/
virtual void requestStop()
{
_stopRequested.store(true);
}
/**
* 检查是否请求停止
* @return true 表示应停止运行
*/
bool isStopRequested() const
{
return _stopRequested.load();
}
/**
* 检查线程是否正在运行
* @return true 表示线程函数正在执行
*/
bool isRunning() const
{
return _isRunning.load();
}
/**
* 检查 std::thread 是否可连接(joinable)
* @return true 表示可以 join
*/
bool joinable() const
{
return _thread.joinable();
}
};