C ++ multithreading (2) matters needing attention

  1. The incoming parameter of the thread (function), the reference & will be invalid, and the pointer * will still pass the address.
  2. To pass a real reference, you need to use std :: ref (param_nanm)
thread thread_obj(func,std::ref(num))

 

  1. If the main thread destroys the variable memory, the child thread will run wrong, so try not to pass the pointer in the main thread in the detach () thread
  2. In order to prevent the main thread from ending first, the detach () thread has not yet been constructed. The copy structure of the calling class to be displayed when the construction is called , that is, to prevent the main thread from ending first, only a copy of memory is required.
class A 
{A (int a) {} 
    A ( const A & a) {cout << " copy constructor " << end;}        
} 

void func (A & a) {} 

int main () { 
   int num = 1; 
   thread thread_obj (func, A ( num )); // here must be converted explicitly, can not be implicitly converted to function 
   thread_obj.detach (); 
   return  0 ; 
}
  1. Get thread ID
std::this_thread::get_id()

      Smart pointer std :: move (smart pointer)

 

Guess you like

Origin www.cnblogs.com/long5683/p/12688896.html