Parameter passing of the thread function and thread ownership transfer (2.2)--std::move () __ function

Source: Internet
Author: User

(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.





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.