一个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; }