[多线程] C++11 thread对象的join()和detach()的区别 & thread没有join()导致进程崩溃

文章讲述了在C++编程中,忘记调用join()或detach()可能导致进程崩溃。实验显示,当主线程结束时,若子线程未明确结束,不使用join()会导致错误。join()确保线程执行完毕后主线程继续,detach()使线程独立运行。
摘要由CSDN通过智能技术生成

之前写代码的时候,忘记写join(),结果进程崩溃了。
这篇文章记录一下join()的必要性。

环境

Virutal Studio 2022

无join()和detach()

#include <iostream>
#include <mutex>

static bool bRunning = true;
static bool bdata = true;

std::mutex mtx;

void _func(void)
{
    
    do{
        std::unique_lock<std::mutex> ulk(mtx);
        std::cout << std::this_thread::get_id() << std::endl;
    } while (bRunning);
}

int main()
{
    std::thread th(_func);
    while (bRunning)
    {
        std::lock_guard<std::mutex> lg(mtx);
        std::cout << std::this_thread::get_id() << std::endl;
        bRunning = false;
    }
    //th.detach();
    //th.join();
    return 0;
}

运行结果

程序崩溃。如果在debug模式下,会弹出以下弹窗
在这里插入图片描述

join

代码修改为:

int main()
{
    std::thread th(_func);
    while (bRunning)
    {
        std::lock_guard<std::mutex> lg(mtx);
        std::cout << std::this_thread::get_id() << std::endl;
        bRunning = false;
    }
    //th.detach();
    th.join();
    return 0;
}

运行结果

程序正常退出

detach

代码修改为:

int main()
{
    std::thread th(_func);
    while (bRunning)
    {
        std::lock_guard<std::mutex> lg(mtx);
        std::cout << std::this_thread::get_id() << std::endl;
        bRunning = false;
    }
    th.detach();
    //th.join();
    return 0;
}

运行结果

程序正常退出

原因分析

试验一

这里我怀疑是,主线程在要结束时,子线程还没有结束,没有指定线程的join或者detach运行方式,导致了错误。
在做一个试验,同样不指定join或者detach,但是让子线程sleep 1s,主线程 sleep 3s,看看会报错吗?

#include <iostream>
#include <thread>
#include <Windows.h>

void _func(void)
{
    Sleep(1000);
    std::cout << "child thread:" << std::this_thread::get_id() << std::endl;
}

int main()
{
    std::thread th(_func);

    Sleep(3000);
    std::cout << "father thread:" << std::this_thread::get_id() << std::endl;

    //th.detach();
    //th.join();
    return 0;
}

结果

依然会有上面提到的 debug error 弹窗。
所以和子线程函数是不是执行完了没关系。

找资料

cplusplus.com/reference中,join()和detach()中都提到了,需要调用这两个函数之一,才能安全的销毁。
cplusplus-join
cplusplus-detach

After a call to this function, the thread object becomes non-joinable and can be destroyed safely.
  • 13
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值