目录
thread::native_handle_type(难搞)
thread
头文件:thread
名称空间:std
thread类用于创建线程对象
构造函数
1、默认构造函数
thread() noexcept;//默认构造函数
默认构造函数会构造一个thread对象,但该对象不表示任何可执行的线程,并且不是joinable。
noexcept形如其名地,表示其修饰的函数不会抛出异常。这是因为异常机制会带来一些额外开销,比如函数抛出异常,会导致函数栈被依次地展开,并依帧调用在本帧中已构造的自动变量的析构函数等。
#include <iostream>
#include <thread>
int main(int argc, char*argv[]){
//使用默认构造函数创建对象,non-joinable状态
std::thread th1;
}
2、带形参的构造函数
//带形参的构造函数
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
该构造函数会构造一个thread对象,表示新的可执行的joinable线程。新线程会调用fn,而args用于初始化fn的形参。
fn可以是函数指针、对象成员函数指针,或任何的移动构造函数对象(如定义了opearotr()的类对象),返回值被忽略。
该构造的完成与该fn副本的调用开始同步。
void f1(string str){
cout << str << endl;
}
class A{
public:
void operator()(string str){
cout << str << endl;
}
};
int main(){
thread th1(f1, "我是第一个子线程");//传递函数
auto f2 = [](string str){cout << str << endl;};
thread th2(f2, "我是第二个子线程");//传递lambda表达式
A a;
thread th3(a, "我是第三个子线程");//传递重载了调用运算符()的类对象
th1.join();
th2.join();
th3.join();
return 0;
}
3、拷贝构造函数
thread (const thread&) = delete;
拷贝构造函数被delete,不可用。
4、移动构造函数
thread (thread&& x) noexcept;
将线程x移交给新线程,需要使用std::move()函数。此后,x不在拥有该线程,且处于non-joinable状态,但可以再用赋值运算符将另一个线程移交给x。
int main()
{
auto f = [](string str) {cout << str << endl; };
/*----------------------------------------------*/
thread th1(f, "我是子线程");
if (th1.joinable() == true)
cout << "th1 is joinable" << endl;
else
cout << "th1 is non-joinable" << endl;
/*----------------------------------------------*/
thread th2(move(th1));//移交给新线程th2
if (th1.joinable() == true)
cout << "th1 is joinable" << endl;
else
cout << "th1 is non-joinable" << endl;
/*----------------------------------------------*/
thread th3(f, "我也是子线程");
th1 = move(th3);
if (th1.joinable() == true)
cout << "th1 is joinable" << endl;
else
cout << "th1 is non-joinable" << endl;
/*----------------------------------------------*/
th1.join();
th2.join();
//此时th3不需要等待,因为此时th3为non-joinable
return 0;
}
析构函数
~thread();
析构函数销毁thread对象。当线程是joinable时,销毁线程时将调用terminate()<