多线程编程C+ -----------第2课

文章讨论了在多线程编程中,使用`join()`可能导致主线程阻塞,而`detach()`可以避免阻塞但可能引发资源管理问题。`join()`确保线程执行完毕后再继续主程序,而`detach()`则使线程与主线程分离,可能在主线程释放资源后,子线程无法访问。
摘要由CSDN通过智能技术生成

使用th.join() 等待子线程执行完毕后,主函数再一起执行后面程序,这时候就是进行了堵塞。这好比,其实你要去吃饭了,但你需要等你同学写完这道题,然后一起去吃放。为了提升效率,你不等你同学了(哈哈),你要跟他分离,做分离操作。其实是子线程发起的分离,th.detach();子线程要脱离你了。很好,主线程已经去吃饭了,假如此时外面下大雨,你们只有一把伞,你(主线程)拥有这把伞的所有权(相当于内存资源),你就去吃饭了,子线程没来得及写完题目,然后他没伞,他去不了吃饭了。
总结一下,多线程现在有两个问题:
1.使用th.join() 有可能使得主程序堵塞(使得多线程的意义大大减少)
2.解决问题1,采用th.detach()分离,但又有可能会遇到主程序提取释放了所有资源,子线程无法访问资源(伞),而失效。(如图)

// pthread.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <thread>

using namespace std;

void ThreadMain1() { //子线程1
    cout << "1:thread was begin!!,son's id :" <<this_thread::get_id()<< endl;
    for (int i = 0; i < 10; i++) {
        cout << "thread_1 : ";
        cout << i << endl;
        this_thread::sleep_for(1000ms);
    }
}
void ThreadMain2() { //子线程2
    cout << "2:thread was begin!!,son's id :" << this_thread::get_id() << endl;
    for (int i = 0; i < 10; i++) {
        cout << "thread_2 :" ;
        cout << i << endl;
        this_thread::sleep_for(1000ms);
    }
}
int main()
{       
         cout << " I am father,my ID:" <<this_thread::get_id()<<endl; 
        //子线程id &&//子线程创建
        thread th1(ThreadMain1);  //  子线程在c11(thread) 作为一个对象,初始化,示例名称为th ,类名称 thread
        thread th2(ThreadMain1);
        //th1.join(); //主线程阻塞
        //th2.join();
        th1.detach();
        th2.detach();
        //子线程释
        return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值