1 passing parameters to the thread function is simple, the general form is as follows
void f (int i,std::string const& s);
Std::thread T (f,3, "Hello");
But there are still some special cases, sometimes we want to pass some references, but we find that the object we pass is a copy of the object instead of the object itself, as shown below
void Update_data_for_widget (widget_id w,widget_data& data); 1
void Oops_again (widget_id W)
{
Widget_data data;
Std::thread T (update_data_for_widget,w,data); 2
Display_status ();
T.join ();
Process_widget_data (data); 3
}
It is important to note that the parameters passed in the new process starting with 2 are not the parameters themselves, but the copies of the parameters, if we pass the parameters themselves, so to write
Std::thread T (update_data_for_widget,w,std::ref (data))
Class X
{
Public
void Do_lengthy_work ();
};
X my_x;
Std::thread T (&x::d o_lengthy_work,&my_x); 1
In this code, my_x.do_lengthy_work as a thread function, my_x address 1 as a pointer object to the function, if the function has parameters, you can provide parameters for the member function: the third parameter of the Std::thread constructor is the member function
The first parameter, and so on.
Class X
{
Public
void do_lengthy_work (int num);
};
X my_x;
Std::thread T (&x::d o_lengthy_work,&my_x,num); 1
C + + Concurrent programming 2--passing parameters to thread functions