C++11中std::thread线程实现暂停(挂起)功能

一、封装Thread类

我们基于C++11中与平台无关的线程类std::thread,封装Thread类,并提供start()、stop()、pause()、resume()线程控制方法。

为了让线程在暂停期间,处于休眠,不消耗CPU,我们使用C++11提供的锁和条件变量来实现。

  • std::mutex
  • std::condition_variable

Thread.h

#ifndef THREAD_H
#define THREAD_H

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

class Thread
{
public:
    Thread();
    virtual ~Thread();

    enum State
    {
        Stoped,     ///<停止状态,包括从未启动过和启动后被停止
        Running,    ///<运行状态
        Paused      ///<暂停状态
    };

    State state() const;

    void start();
    void stop();
    void pause();
    void resume();

protected:
    virtual void process() = 0;

private:
    void run();

private:
    std::thread* _thread;
    std::mutex _mutex;
    std::condition_variable _condition;
    std::atomic_bool _pauseFlag;   ///<暂停标识
    std::atomic_bool _stopFlag;   ///<停止标识
    State _state;
};

#endif // THREAD_H

Thread.cpp

#include "Thread.h"
#include <iostream>

using namespace std;

Thread::Thread()
    : _thread(nullptr),
      _pauseFlag(false),
      _stopFlag(false),
      _state(Stoped)
{

}

Thread::~Thread()
{
    stop();
}

Thread::State Thread::state() const
{
    return _state;
}

void Thread::start()
{
    if (_thread == nullptr)
    {
        _thread = new thread(&Thread::run, this);
        _pauseFlag = false;
        _stopFlag = false;
        _state = Running;
    }
}

void Thread::stop()
{
    if (_thread != nullptr)
    {
        _pauseFlag = false;
        _stopFlag = true;
        _condition.notify_all();  // Notify one waiting thread, if there is one.
        _thread->join(); // wait for thread finished
        delete _thread;
        _thread = nullptr;
        _state = Stoped;
    }
}

void Thread::pause()
{
    if (_thread != nullptr)
    {
        _pauseFlag = true;
        _state = Paused;
    }
}

void Thread::resume()
{
    if (_thread != nullptr)
    {
        _pauseFlag = false;
        _condition.notify_all();
        _state = Running;
    }
}

void Thread::run()
{
    cout << "enter thread:" << this_thread::get_id() << endl;

    while (!_stopFlag)
    {
        process();
        if (_pauseFlag)
        {
            unique_lock<mutex> locker(_mutex);
            while (_pauseFlag)
            {
                _condition.wait(locker); // Unlock _mutex and wait to be notified
            }
            locker.unlock();
        }
    }
    _pauseFlag = false;
    _stopFlag = false;

    cout << "exit thread:" << this_thread::get_id() << endl;
}

二、测试代码

main.cpp

#include <QCoreApplication>
#include <iostream>
#include "Thread.h"

using namespace std;

void mySleep(int s)
{
    std::this_thread::sleep_for(std::chrono::duration<double>(s));
}

class MyThread : public Thread
{
protected:
    virtual void process() override
    {
        cout << "do my something" << endl;
        mySleep(1);
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyThread thread;

    cout << "start thread" << endl;
    thread.start();
    cout << "thread state:" << thread.state() << endl;
    mySleep(3);

    cout << "pause thread" << endl;
    thread.pause();
    cout << "thread state:" << thread.state() << endl;
    mySleep(3);

    cout << "resume thread" << endl;
    thread.resume();
    cout << "thread state:" << thread.state() << endl;
    mySleep(3);

    cout << "stop thread" << endl;
    thread.stop();
    cout << "thread state:" << thread.state() << endl;
    mySleep(3);

    return a.exec();
}

运行结果:

在这里插入图片描述



若对你有帮助,欢迎点赞、收藏、评论,你的支持就是我的最大动力!!!

同时,阿超为大家准备了丰富的学习资料,欢迎关注公众号“超哥学编程”,即可领取。

本文涉及工程代码,公众号回复:16PauseStdThread,即可下载。

在这里插入图片描述

  • 9
    点赞
  • 74
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百里杨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值