/**
* By kkmd66
*
* 理论学习
* 1、主线程是什么?什么时候开始、结束?
* 2、子线程如何创建?生命周期是什么?
* 3、thread类的基本使用方法
*
*
* 代码演示
* 1、线程ID区分不同的线程
* 2、join、detach区别
*/
#include <iostream>
//使用多线程头文件
#include <thread>
#include <list>
#include <vector>
using namespace std;
void putInData(){
cout << "putInData 子线程 id = " << this_thread::get_id() << endl;
for (int i = 0; i < 100; i++){
cout << "putInData 子线程:放入一个数据" << i << endl;
//std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
}
//主线程从main函数入口开始执行
int main(){
cout << "主线程 id = " << this_thread::get_id() << endl;
//std::list<int> dataQuene;
//1、创建并开启线程,线程入口是putInData, takeOutData 函数
thread putThread(putInData);
//2、join()阻塞主线程并等待子线程执行完,当子线程执行完毕,join()就执行完毕,主线程继续往下执行
//join意为汇合,子线程和主线程汇合
putThread.join();
//3、传统多线程程序中,主线程要等待子线程执行完毕,然后自己才能向下执行
//如果返回true,证明可以调用join()或者detach()
//如果返回false,证明调用过join()或者detach(),join()和detach()都不能再调用了
//if (putThread.joinable()){
// cout << "可以调用join()或者detach()" << endl;
// putThread.join();
//}
cout << " Hello, thread! " << endl;
return 0;
}
谁调用了这个函数?
调用了这个函数的线程对象,就是putThread,一定要等这个线程的活干完了,这个join()函数才能得到返回。
在什么线程环境下调用了这个函数?
必须要等线程方法执行完毕后才能返回,那还必然是阻塞调用线程的,也就是说如果一个线程对象putThread在一个线程环境main调用了这个函数,那么这个线程环境main就会被阻塞,直到整个线程对象putThread在构造时传入的方法执行完毕后,才能继续往下走。
//ORB-SLAM3中的应用案例
//Launch threads to compute in parallel a fundamental matrix and a homography
vector<bool> vbMatchesInliersH, vbMatchesInliersF;
float SH, SF;
cv::Mat H, F;
thread threadH(&TwoViewReconstruction::FindHomography, this, ref(vbMatchesInliersH), ref(SH), ref(H));
thread threadF(&TwoViewReconstruction::FindFundamental, this, ref(vbMatchesInliersF), ref(SF), ref(F));
//Wait until both threads have finished
threadH.join();
threadF.join();
std::ref:为了解决在线程的创建等过程的值拷贝问题
实践总结
1、main函数开始后自动开启主线程
2、进程id,this_thread::get_id()可以查看线程id
3、threads类可以创建线程。创建后自动开启线程,线程入口可以是函数、类、lambda表达式
4、join,意为汇合,子线程和主线程汇合。阻塞主线程并等待子线程执行完,当子线程执行完毕,join()就执行完毕
5、detach,分离,主线程不再与子线程汇合,不在等待子线程
最后
有问题随时与我交流~
vx :kkmd66-2