C++智能指针与线程配合使用方法,附测试代码

当智能指针 shared_ptr 在类里使用时,他的释放是在析构函数中内容执行完之后。

当使用 shared_ptr 开启了一个线程,这个线程也会在析构函数中内容执行完之后被释放,也就是被delete掉,如果线程尚未 join 的话就会报错,所以要先在析构函数里join线程。

见测试代码。这样管理堆上的线程是不是很优雅?


#include <thread>
#include <iostream>
#include <memory>
#include <atomic>
#include <vector>
struct/*class*/ ShowThread
{
private:
    std::atomic<bool> m_stop = false;
    std::vector<std::shared_ptr<std::thread>> spthArray;
    void showmsg(std::string msg) {
        while(!m_stop){
            std::cout << msg << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(200));
        }
    }
public:
    ShowThread() {
        for (int i = 0; i < 10; i++) {
            char str[12];
            memset(str, '\0', 12); _itoa_s(i,str,10);std::string str_s = str;
            std::shared_ptr<std::thread> spth = std::make_shared<std::thread>(&ShowThread::showmsg, this, str_s);
            spthArray.push_back(spth);
        }
    }
    ~ShowThread() {
        //调用析构函数时,会先执行析构函数内的内容
        m_stop = true;
        for (auto it = spthArray.begin(); it != spthArray.end(); it++) {
            it->get()->join();
        }
        //执行完析构函数内容后,会执行释放智能指针的操作
    }
};
int main()
{
    ShowThread ST;
    system("pause");
    std::cout << "Hello World!\n";
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值