目录
一、主线程和子线程
主线程从main函数开始执行;
我们的自己创建的线程从一个函数开始执行(初始函数),这个函数执行完成,则这个线程执行完毕。
主线程执行完毕,则这个进程执行完毕。
一般情况下,主线程执行完毕,子线程还未执行完毕,则会强行结束子线程。
想要让子线程一直执行,则要主线程一直执行。
二、自己创建子线程
步骤:
1.添加头文件thread;
2.写初始函数;
3.main函数中写代码。
三、join
例子1:创建子线程,
#include <iostream>
#include <thread> //库文件
using namespace std;
void myprint(){
cout<<"my thread starts"<<endl;
//
cout<<"my thread end "<<endl;
}
int main() {
//myprint是可调用对象
//创建新线程,线程的起点是myprint
//创建一个子线程,同时子线程开始执行
thread myThread(myprint);
//join阻塞主线程,等待子线程执行完
myThread.join();
cout << "Hello, World!" << std::endl;
return 0;
}
三、detach
主线程和子线程分离。主线程不用等待子线程结束,主线程结束后,子线程可以继续执行(在后台执行,在LInux中叫守护线程)。
主线程结束后,子线程由C++运行时库接管,运行结束后,运行时库清理相关资源。
四、joinable
判断是否使用join或者detach,可以返回True,否则返回False。
join 后不能在detach
detach 后也不能join.
例子2:detach,joinable
#include <iostream>
#include <thread>
using namespace std;
void myprint(){
cout<<"my thread start"<<endl;
//
cout<<"my thread end "<<endl;
}
int main() {
thread myThread(myprint); //creat a thread
if(myThread.joinable()){
cout<<"1.joinable is True"<<endl;
myThread.detach();
}
else{
cout<<"1.joinable is False"<<endl;
}
cout << "Hello, World!" << std::endl;
cout << "Hello, World!" << std::endl;
return 0;
}
五、可调用对象作为参数
函数:
thread的参数为可调用对象。
类对象:
#include <iostream>
#include <thread>
using namespace std;
class TA{
public :
TA(int i):m_i(i){
cout<<"this is Constructor"<<endl;
}
~TA(){
cout<<"this is Destructor"<<endl;
}
void operator() (){
cout<<"my thread1 start"<<endl;
cout<<"the number is "<<m_i<<endl;
cout<<"my thread1 end "<<endl;
}
private:
int m_i;
//用引用的方式构造
//in &m_i;
};
void myprint(){
cout<<"my thread2 start"<<endl;
//
cout<<"my thread2 end "<<endl;
}
int main() {
int i = 6;
TA ta(i);
thread myThread1(ta);
//thread myThread2(myprint); //creat a thread
if(myThread1.joinable()){
cout<<"1.joinable is True"<<endl;
myThread1.join();
//当使用detach的时候,结构体构造函数不能使用引用,因为主线程结束以后
//引用内容就被销毁了
//myThread1.detach();
}
else{
cout<<"1.joinable is False"<<endl;
}
cout << "Hello, World!" << std::endl;
cout << "Hello, World!" << std::endl;
return 0;
}
主线程结束了,用的对象就不在了,ta会销毁。子线程尽量不要用引用。
主线程结束不会影响子线程的调用,因为是将对象复制到线程中的,所复制的TA 仍然存在。
lambda函数: