c++11 detach()子线程对象生命周期分离

说明:

  • detach():分离,主线程不与子线程汇合,各自独立自行,主线程结束,子线程也能够运行;
  • 一旦detach()后,与这个线程关联的thread对象就会失去与这个主线程的关联,此时子线程就会驻留后台运行;
  • 这个子线程将会被系统运行时库接管,当这个子线程执行完成后,由运行时库负责清理该线程相关的资源(守护线程)
  • 使用detach将会失去对线程的控制,join与detech不能同时使用
#include <thread>
#include <iostream>

using namespace std;
void thread_fun()
{
    cout << "sub thread begin,thread ID: " << this_thread::get_id() << endl;
    for (int i = 0; i < 10; i++) {
        cout << "i= " << i << endl;
        this_thread::sleep_for(chrono::seconds(1)); // 1000ms
    }
    cout << "sub thread is over,thread ID: " << this_thread::get_id() << endl;
}
int main(int argc, char *argv[])
{
    cout << "main thread begin,thread ID: " << this_thread::get_id() << endl;
    thread th(thread_fun);
    th.detach(); //子线程与主线程分离 守护线程,主线程退出后 子线程不一定退出

    cout << "main thread is over,thread ID: " << this_thread::get_id() << endl;
    return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值