C++11 custom thread class implements thread start, pause and stop

#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <atomic>
#include <condition_variable>

class MyThread {
public:
    MyThread() : m_running(false), m_paused(false) {}
    virtual ~MyThread() {}

    // 启动线程
    void start() {
        if (!m_running) {
            m_running = true;
            m_thread = std::thread(&MyThread::run, this);
        }
    }

    // 暂停线程
    void pause() {
        m_paused = true;
    }

    // 继续线程
    void resume() {
        m_paused = false;
        m_cv.notify_one();
    }

    // 停止线程
    void stop() {
        if (m_running) {
            m_running = false;
            m_paused = false;
            if (m_thread.joinable()) {
                m_thread.join();
            }
        }
    }

    // 线程入口函数
    virtual void run() {
        while (m_running) {
            if (!m_paused) {
                doWork();
            }
            else {
                std::unique_lock<std::mutex> lock(m_mutex);
                m_cv.wait(lock, [this]() { return !m_paused || !m_running; });
            }
        }
    }

    // 执行工作函数,需要子类来实现
    virtual void doWork() = 0;

private:
    std::thread m_thread;
    std::atomic<bool> m_running; // 原子变量,标记是否运行中
    std::atomic<bool> m_paused; // 原子变量,标记是否暂停中
    std::mutex m_mutex;
    std::condition_variable m_cv;
/*
在 run() 函数中,当线程被暂停时,使用了条件变量来等待通知。这样可以避免线程占用过多的 CPU 时间。同时,为了线程的安全,在 m_running 和 m_paused 变量前加上了 std::atomic<bool> 定义,保证了对它们的操作是原子的,从而避免了数据竞争问题。
*/
};

class MyWorkerThread : public MyThread {  //继承 MyThread 类并实现 doWork() 函数
public:
    virtual void doWork() {
        // do some work
        std::cout << "Hello from MyTask!\n";
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
};

 
int main() {

    MyWorkerThread myThread;
    myThread.start();//启动线程
    std::cout << "will run 5s !\n";
    std::this_thread::sleep_for(std::chrono::seconds(5));

    myThread.pause();//暂停线程
    std::cout << "will pause 6s !\n";
    std::this_thread::sleep_for(std::chrono::seconds(6));

    myThread.resume();//继续线程
    std::cout << "resume, will run 6s !\n";
    std::this_thread::sleep_for(std::chrono::seconds(6));

    myThread.stop();//停止线程

 
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_26093511/article/details/131287043