std::thread 用于创建一个执行的线程实例,所以它是一切并发编程的基础,使用时需要包含头文件#include<thread>,它提供了很多基本的线程操作,例如get_id()来获取所创建线程的线程 ID,例如使用 join() 通知主线程等待其他线程退出,detach脱离主线程。例如:
#include <iostream>
#include <thread>
using namespace std;
void fun1()
{
cout << "hello world hello fun" << endl;
}
void fun(int a)
{
cout << "hello thread" << a << endl;
}
int main()
{
cout << thread::hardware_concurrency() << endl;//该函数获取cpu核心数,用于确定线程的数量
thread t1(fun1);//创建线程t1,并执行fun1函数
thread t2(fun,100);//函数传参
thread t3([]()
{
cout << "hello world hello thread" << endl;
});//lambda表达式,匿名函数
cout << t1.joinable() << endl;//判断该线程是否可以join()
//当线程也叫join()或者是detach()时,该函数返回0
t1.join();//join函数用于让主线程等待子线程退出
//否则主线程退出会让子线程直接退出,产生错误
t2.join();
t3.detach();//脱离主线程,成为孤儿线程。当主线程退出时该线程将继续运行
cout << t1.joinable() << endl;
cin.get();//主线程阻塞等待
}