C++ std::shared_ptr智能指针以及多线程中与弱指

2019-05-22  本文已影响0人  b036101467d7
#include <iostream>
#include <thread>
#include <chrono>

class CTool {
public:
    CTool(int startCount) : mCount(startCount) {}
    ~CTool() {
        std::cout << "~CTool Destruction" << std::endl;
    }
    
    void success() {
        std::cout<<"Tool lock success: " << mCount++ << std::endl;
        
    }
private:
    int mCount;
};

class CTest {
public:
    CTest():mExit(false){}
    ~CTest(){};
    void setTool(std::weak_ptr<CTool> tool);
    void start();
    void run();
    void release();
private:
    std::weak_ptr<CTool> mTool;
    std::thread mThread;
    bool mExit;
};

void CTest::run() {
    //线程B
    while(!mExit) {
        //lock成功,sp为shared_ptr类型;失败为null,则表示mTool已被强引用者释放
        if(auto sp = mTool.lock()) {
            sp->success();
        }else{
            std::cout << "Tool lock fail!" << std::endl;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
}

void CTest::setTool(std::weak_ptr<CTool> tool) {
    mTool = tool;
}

void CTest::start() {
    mThread = std::thread(&CTest::run, this);
}

void CTest::release() {
    mExit = true;
    if(mThread.joinable()) {
        mThread.join();
    }
}


int main(int argc, const char * argv[]) {
    //主线程A
    std::shared_ptr<CTest> mTest = std::make_shared<CTest>();
    {
        //mTool在花括号内有效
        std::shared_ptr<CTool> mTool = std::make_shared<CTool>(100);
        mTest->setTool(mTool);
        mTest->start();
        std::this_thread::sleep_for(std::chrono::seconds(5));
    }
    //出花括号,mTool自动调用析构释放
    std::cout << "after mTool destroy!" << std::endl;

    std::this_thread::sleep_for(std::chrono::seconds(5));

    mTest->release();
    
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读