第一天:简单了解如何创建线程
1、创建线程,引入头文件
#include<iostream>
#include<thread>
using namespace std;
thread
2、创建一个函数HelloWorld:
void HelloWorld()
{
cout<<"Hello World"<<endl;
}
3、创建线程h
int main()
{
//创建线程h
thread h(HelloWorld);
cout<<"Good Day"<<endl;
//等待新线程执行完毕
h.join();
return 0;
}
4、结果:
(1)添加join结果如下:
(2)未添加join,返回结果如下:
二、先调用jointable判断线程是否有效,返回值为bool值,使用joinable,可以避免一些潜在错误,让线程使用更安全:
int main()
{
//创建线程h
thread h(HelloWorld);
cout<<"Good Day"<<endl;
//等待新线程执行完毕
bool ok=h.joinable();
{
if(ok)
{
h.join();
}
}
return 0;
}
运行结果如下: