1、std::thread
在C++11之前,C++语言层面是不支持多线程的,想利用C++实现并发程序,借助操作系统的API实现跨平台的并发程序存在着诸多不便,当C++11在语言层面支持多线程后,编写跨平台的多线程代码就方便了许多。
C++11提供的std::thread
在开发多线程方面带来了便捷。
#include <iostream>
#include <thread>
void threadfunc()
{
std::cout << "thread func" << std::endl;
}
int main()
{
std::thread t1(threadfunc);
t1.join(); //等待threadfunc运行结束
return 0;
}
首先定义线程对象t1
,线程函数threadfunc
运行在线程对象t1
中,当线程创建成功并执行线程函数后,一定要保证线程函数运行结束才能退出,这里调用了join()
函数阻塞线程,直到threadfunc()
运行结束,回收对应创建线程的资源。如果不阻塞线程,就不能保证线程对象t1
在threadfunc()
运行期间有效,下面不调用join()
阻塞线程。
#include <iostream>
#include <thread>
void threadfunc()
{
std::cout << "thread func" << std::endl;
}
int main()
{
std::thread t1(threadfunc);
//t1.join(); //等待threadfunc运行结束
return 0;
}
在运行时引起了程序崩溃。
除了调用join()
阻塞线程,保证线程对象在线程函数运行期间的有效性,还可以通过线程分离的手段实现,调用detach()
函数使得线程对象与线程函数分离,这样,在线程函数运行期间,线程对象与线程函数就没有联系了,此时的线程是作为后台线程去执行,detach()
后就无法再和线程发生联系,也不能通过join()
来等待线程执行完毕,线程何时执行完无法控制,它的资源会被init
进程回收,所以,通常不采用detach()
方法。
#include <iostream>
#include <thread>
void threadfunc()
{
std::cout << " detach thread func" << std::endl;
}
int main()
{
std::thread t1(threadfunc);
t1.detach(); //线程分离
return 0;
}
这里调用detach()
实现线程分离,但是运行后,主线程退出的时候threadfunc()
还没有输出“detach thread func”
,threadfunc()
什么时候运行结束也无法确定,为了看到所创建的线程运行结果,在主线程等待一下再退出。
#include <iostream>
#include <thread>
#include <chrono> //时间
void threadfunc()
{
std::cout << "detach thread func" << std::endl;
}
int main()
{
std::thread t1(threadfunc);
t1.detach();
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));//睡眠1000毫秒
break;
}
return 0;
}
此时运行结果:
detach thread func
通过std::thread
创建的线程是不可以复制的,但是可以移动。
#include <iostream>
#include <thread>
#include <chrono>
void threadfunc()
{
std::cout << "move thread func" << std::endl;
}
int main()
{
std::thread t1(threadfunc);
std::thread t2(std::move(t1));
t2.join();
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));//睡眠100