使用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;
}