(1) First code:
void f (int i,std::string const & s);
Std::thread T (F, "Hello");
The first argument is the name of the thread function, and the second parameter is the parameter of the function. Note, however, that when the parameter is supplied as a pointer to an automatic variable, such as:
VOID fn (int i, std::string const & s);
void opp (int some_param)
{
char buffer[1024];
sprintf (buffer, "%i", Some_param);
Std::thread T (FN, 3, buffer);
T.detach ();
}
The pointer to the local variable buffer is passed to the new thread, which takes a moment, and if the thread function exits before the buffer is converted to std::string, the solution is:
Std::thread T (FN, 3, (std::string) buffer)//This avoids the buffer suspension pointer
(2) There is also a situation where the object is copied, but we want the reference, the result variable copy changed, and the variable actually does not change.
void Update_data (widget_id W, widget_data& data);
void Opp_again (widget_id W)
{
widget_data data;
Std::thread T (Update_data, W, data);
Display_status ();
T.join ();
Process_widget_data (data);//data value does not change
}
In fact, and the parameters of the function is very consistent, our solution is:
Std::thread T (Update_data, W, std::ref (data));
(3) The ownership transfer of the thread, Std::thread is not replicable, but is removable movable, that is, can transfer the ownership of the thread, but a thread can only have one ownership.
void Some_function ();
void Some_other_function ();
Std::thread T1 (some_function);
Std::thread T2 (Std::move (t1));//Show transfer ownership
T1 = Std::thread (some_other_function); Implicit transfer of ownership
std::thread t3 = std::move (T2);
T1 = std::move (T3);
Of course, we can put multiple threads inside a vector for easy management.