C++ 多线程(2)注意事项

  1. 线程(函数)的传入参数,引用&会失效,指针*还是会传递地址。
  2. 想要传递真正的引用需要使用std::ref(param_nanm)
thread thread_obj(func,std::ref(num))
  1. 因为主线程如果销毁了变量内存,子线程的运行就会出错,因此尽量不要在detach()的线程中用传递主线程中的指针
  2. 为了防止主线程先结束,detach()的线程还没构造,调用构造的时候要显示的调用类的拷贝构造,即为了防止主线程先结束,只有复制一份内存才行
class A
{  A(int a){}
    A(const A & a){cout<<"拷贝构造函数"<<end;}       
}

void func(A &a){}

int main(){
   int num=1;
   thread thread_obj(func,A(num));//这里必须显示地转换,不能交给函数隐式转换
   thread_obj.detach();
   return 0;
}
  1. 获取线程ID
std::this_thread::get_id()

      智能指针std::move(智能指针)

猜你喜欢

转载自www.cnblogs.com/long5683/p/12688896.html