一个是实力的体现,一个是商用的必须需求。
以往:
windows: CreatThread(),_beginthred(),_beginthredexe()
Linux: pthread_create() 创建线程
临界区,互斥量。以往多线程代码不能跨平台。
从C++11开始,C++语言本身增加可移植性。
整个进程是否执行完毕的标志是主线程是否执行完毕。此时,如果主线程执行完毕,但是其他子线程还没有执行完毕,那么,这些子线程也会被操作系统强行终止。
1.包含头文件:
#include<thread>
2.创建一个线程函数
void myprint()
{
cout << "线程开始运行" << endl;
//...
//...
//...
cout << "线程执行完毕" << endl;
}
3.main中开始写代码
std::thread mythread(myprint);
mythread.join();//阻塞主线程,让主线程等待
传统多线程:等待子线程执行完毕,然后自己最后在退出。
detach():主线程可以不等子线程执行完毕,就结束程序。此时子线程跑到系统的后台运行,相当于被C++运行时库接管,当这个子线程执行完成后,由运行时库负责清理相关资源。
一旦detach(),就不能join(),否则会出现异常。
void myprint()
{
cout << "线程开始运行" << endl;
cout << "1" << endl;
cout << "2" << endl;
cout << "3" << endl;
cout << "4" << endl;
cout << "5" << endl;
cout << "线程执行完毕" << endl;
}
std::thread mythread(myprint);
mythread.detach();//一起打印,但是主线程完毕后,就结束程序
cout << "hello world" << endl;
joinable():判断能不能使用join或detach。
std::thread mythread(myprint);
if(mythread.joinable())
mythread.join();
else
mythread.detach();
cout << "hello world" << endl;
线程参数:当线程引入参数时,是以复制的形式,
class T {
int i;
public:
T(int j):i(j)
{
cout << "构造函数执行" << endl;
}
T(const T &j)
{
i = j.i;
cout << "拷贝构造函数执行" << endl;
}
void operator()()
{
cout << "i=" << i << endl;
}
~T()
{
cout << "析构函数执行" << endl;
}
};
auto thread = [] {
cout << "线程开始执行" << endl;
};
std::thread mythread(thread);
if(mythread.joinable())
mythread.join();
else
mythread.detach();
cout << "hello world" << endl;