1. thread header
#include <thread>
2. 构造函数原型
default (1) thread() noexcept;
initialization (2) template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
copy [deleted] (3) thread (const thread&) = delete;
move (4) thread (thread&& x) noexcept;
2.1 参数说明
Fn: 函数指针、成员函数指针、函数对象,如果函数有返回值,将被忽略。
args: 调用Fn函数时传递的参数,如果Fn是指向成员函数,则第一个参数应该传递该成员函数所属的对象的指针或引用
3. 创建thread对象
thread t_empty; // 调用默认构造函数,不代表任何可执行的线程
4. 用一个函数初始化thread
#include <iostream>
#include <thread>
using namespace std;
void threadFunc()
{
cout << "Welcome to Multithreading" << endl;
}
int main( )
{
std::thread funcTest1(threadFunc);
return 0;
}
运行结果:
Starting /home/rootroot/Learn/C++/MultiThread/multiThread/slamtest…
terminate called without an active exception
The program has unexpectedly finished.
/home/rootroot/Learn/C++/MultiThread/multiThread/slamtest crashed
运行出错,因为funcTest1线程没有在main函数结束前结束。
要解决此问题,可以使用 join() 函数解决。
该函数仅仅在对应线程执行结束后才会返回。
int main( )
{
std::thread funcTest1(threadFunc);
funcTest1.join(); // 线程结束后才会返回
return 0;
}
在 join() 返回后,该线程变为 ** not joinable** ,
当线程由默认构造函数构建 或者 move/赋值给另一个线程 或者 join() or detach()成员函数被调用,在这三种情况下,此线程是不可 join() 的。
参考:
https://www.tutorialcup.com/cplusplus/multithreading.htm
http://www.cplusplus.com/reference/thread/thread/