包含头文件
(拒绝自闭VS2010版本,不支持该头文件)
#include <thread>
写一个子线程
事先说明:
1.一般来说,子线程也要从一个函数开始执行,所以创建一个线程的同时,我们要声明一个函数
2.一般情况下,主线程运行完毕后,未完成的子线程会被系统强行关闭
方法一:声明函数
首先声明一个子线程的函数,其次在主线程中定义一个thread类指向这一子线程,即完成了子线程的创建,如例2-1
例2-1
#include <iostream>
#include <thread>
//1.声明一个子线程的函数
void func()
{
std::cout << "My process is beginning" << std::endl;
//...
//...
std::cout << "My process is finished" << std::endl;
}
int main()
{
std::thread pro(func); //2.在主线程中定义一个thread类指向这一子线程,这类似于构造器
pro.join(); //3.主线程等待子线程执行完成语句(后面会提到)
std::cout << "Main process is finished\n";
return 0; //4.退出主线程
}
tips:
1.std::thread()括号中声明的是一个可调用对象
2.注释2中的语句执行的是,创建一个线程,确定线程执行起点,并使其开始执行
方法二:创建类
方法三:lambda表达式
方法四:成员函数作线程函数
举个例子
//先声明一个类
class A
{
public:
A() {}
~A() {}
// 需要声明一个可调用对象
void operator()()
{
cout << "我点线程得到了执行" << endl;
cout << "我的线程结束了执行" << endl;
}
}
int main()
{
A Myclass;
std::thread thrd3(Myclass);
thrd3.join();
return 0
}
thread类下的几个方法
一、join()
作用:
阻塞主线程,让主线程等待子线程执行完毕后,再继续执行主线程。
再举一个例子3-1 (声明了两个线程func1和func2)
#include <iostream>
#include <thread>
void func1()
{
std::cout << "My process is beginning" << std::endl;
std::cout << "My process is finished" << std::endl;
}
void func2()
{
std::cout << "My process2 is beginning" << std::endl;
std::cout << "My process2 is finished" << std::endl;
}
int main()
{
std::thread pro(func1);
std::thread pro2(func2);
pro.join();
pro2.join();
std::cout << "Main process is finished\n";
return 0;
}
tips:
多执行几遍,发现输出的结果并不是一样的,这个例子另外说明的是,线程的处理顺序是随机的
二、detch()
分离主线程和子线程之间的关系,主线程的结束不再影响子线程的运行
分离之后,子线程留给后台运行,相当于子线程被C++运行时库接管,子线程执行完毕后,由运行时库负责清理该线程相关的资源
注:被分离之后,不能够再使用join()方法
例子3-2
#include <iostream>
#include <thread>
void func1()
{
std::cout << "My process is beginning" << std::endl;
std::cout << "My process is running1" << std::endl;
std::cout << "My process is running2" << std::endl;
std::cout << "My process is running3" << std::endl;
std::cout << "My process is running4" << std::endl;
std::cout << "My process is running5" << std::endl;
std::cout << "My process is running6" << std::endl;
std::cout << "My process is finished" << std::endl;
}
int main()
{
std::thread pro(func1);
//std::thread pro2(func2);
pro.detach();
//pro2.join();
for (int i = 0; i < 5; i++)
{
std::cout << i << std::endl;
}
std::cout << "Main process is finished\n";
return 0;
}
我们发现,多执行几遍,结果也不一样
三、joinable()
判断是否可以使用join()或detch()方法,可以返回ture,不可以返回false