1 。拷贝构造函数
thread(const thread&) = delete;
拷贝构造函数被禁用,std::thread对象不可拷贝构造
2 。Move构造函数
thread(thread&& x)noexcept
调用成功原来x不再是std::thread对象
void threadFun(int& a)
{
cout << "this is thread fun !" << endl;
}
int value = 2;
thread t1(threadFun, std::ref(value));
thread t2(std::move(t1));
t2.join();
3。get_id()
获取线程ID,返回类型std::thread::id对象。
thread t1(threadFun);
thread::id threadId = t1.get_id();
cout << "线程ID:" << threadId << endl;
//threadId转换成整形值,所需头文件<sstream>
ostringstream oss;
oss << t1.get_id();
string strId = oss.str();
unsigned long long tid = stoull(strId);
cout << "线程ID:" << tid << endl;
4。 创建线程,引用传参 std::ref()
void threadFun1(int& v)
{
cout << "this is thread fun1 !" << endl;
cout << v << endl;
}
int main()
{
int value = 6;
thread t1(threadFun1, std::ref(value));
t1.join();
getchar();
return 1;
}
5。创建线程,函数对象参数格式
struct fun_obj
{
void operator() () { do_something(); };
}
std::thread td(fun_obj());//函数声明
std::thread td((fun_obj()));//创建线程
std::thread td{ fun_o bj() };//创建线程
fun_obj obj;
std::thread td(obj);//创建线程
6。线程参数:函数对象、引用、字符串(字面值/char*/string隐式转换问题)