一个C++的 线程基类
#include <iostream> #include <thread> #include <mutex> #include <condition_variable> #include <atomic> class ThreadBase { public: ThreadBase() : thread_(nullptr), stopFlag_(false) {} virtual ~ThreadBase() { stop(); } // 启动线程 void start() { std::lock_guard<std::mutex> lock(mutex_); if (!thread_) { stopFlag_ = false; thread_ = new std::thread(&ThreadBase::run, this); } } // 停止线程 void stop() { { std::lock_guard<std::mutex> lock(mutex_); if (thread_) { stopFlag_ = true; cv_.notify_all(); } } if (thread_ && thread_->joinable()) { thread_->join(); } { std::lock_guard<std::mutex> lock(mutex_); delete thread_; thread_ = nullptr; } } protected: // 子类需要实现的业务逻辑 virtual void threadFunction() = 0; // 判断线程是否需要停止 bool shouldStop() const { return stopFlag_.load(); } // 等待指定时间(毫秒) void waitFor(int milliseconds) { std::unique_lock<std::mutex> lock(mutex_); cv_.wait_for(lock, std::chrono::milliseconds(milliseconds), [this] { return stopFlag_.load(); }); } private: void run() { while (!shouldStop()) { threadFunction(); } } std::thread* thread_; std::mutex mutex_; std::condition_variable cv_; std::atomic<bool> stopFlag_; }; class MyThread : public ThreadBase { protected: void threadFunction() override { // 模拟执行一些任务 std::cout << "MyThread is running..." << std::endl; // 模拟任务执行时间 waitFor(1000); // // 可选择在某个条件下停止 // if (/* some condition */) { // stop(); // 手动停止线程 // } } }; int main() { MyThread myThread; myThread.start(); std::this_thread::sleep_for(std::chrono::seconds(5)); // 主线程等待一段时间 myThread.stop(); // 停止子线程 return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?