C + + Concurrent programming 2--passing parameters to thread functions

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.