C++线程类封装实例

先上代码:

class Thread : NoCopy{
    Thread():_quit(false), _isRunning(false){}
    vartual ~Thread(){}

    int start(bool isJoin = false){    //默认是detach模式
        if(_isRunning){
            return -1;        
        }
        
                _quit = false;
#ifdef SUPPORT_CPLUSPLUS11
        std::thread thd(&Thread::work_thread, this);

        if (isJoin) {
            thd.join();
        } else {
            thd.detach();
        }

#else
        int ret = pthread_create(&_thread_t, NULL, work_thread, (void*)this);

        if (ret != 0) {
            return -2;
        }

        if (isJoin) {
            void* threadResult = 0;
            ret = pthread_join(_thread_t, &threadResult);

            if (ret != 0) {
                return -3;
            }
        } else {
            ret = pthread_detach(_thread_t);

            if (ret != 0) {
                return -4;
            }
        }

#endif
        return 0;
    }

    bool isQuit() const{
        _qiut = true;

        if(isWaiting){
            while(_isRunning){
                msleep(10);
            }        
        }
    }

    bool isRunning() const {
        return _isRunning;
    }

    static void msleep(int ms) {
#ifdef SUPPORT_CPLUSPLUS11
        std::this_thread::sleep_for(std::chrono::milliseconds(ms));
#else
        usleep(ms * 1000);
#endif
    }

protected:
    //必须被子类实现
    virtual void run() = 0;

private:
#ifdef SUPPORT_CPLUSPLUS11
    void work_thread() {
        _isRunning = true;
        run();
        _isRunning = false;
    }
#else
    static void* work_thread(void* param) {
        Thread* pThis = (Thread*)param;
        pThis->_isRunning = true;
        pThis->run();
        pThis->_isRunning = false;
    }
#endif

private:
#ifdef SUPPORT_CPLUSPLUS11
    std::atomic<bool> _quit;

    std::atomic<bool> _isRunning;
#else
    volatile bool _quit;

    volatile bool _isRunning;

    pthread_t _thread_t;
#endif
};

用法示例:

class myThread:public Thread{
public:
    myThread(){}
    ~myThread(){}

protected:
    void run(){
        while(!isQuit()){
            //do something
        }
    }

};


int main(){
    myThread thread;
    thread.start();

    thread.quit(true);//可以选择是否等待线程结束,默认是等待     

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值