C++11 Threading Guide (v)--the implementation of thread's moving semantics

Source: Internet
Author: User

1. The thread's move semantics implementation is based on the move semantics described in the previous chapters, which we use to implement threading.
#include <iostream> #include <thread> #include <vector> #include <algorithm> #include < Cassert>int Main () {std::vector<std::thread> workers;for (int i = 0; i < 5; i++) {Auto T = std::thread ([i] () {St D::cout << "thread function:" << i << "\ n";}); Workers.push_back (Std::move (t));} Std::cout << "Main thread\n"; Std::for_each (Workers.begin (), Workers.end (), [] (Std::thread &t) {assert ( T.joinable ()); T.join ();}); return 0;}
The result of the operation is:
Thread Function:thread function:thread function:01

Thread Function:3
2
Main thread
Thread Function:4
Next, make some changes to the code. Separate the thread function task ().
#include <iostream> #include <thread> #include <vector> #include <algorithm> #include < cassert>void Task (int i) {std::cout<< "worker:" <<I<<STD::ENDL;} int main () {std::vector<std::thread> workers;for (int i = 0; i < 5; i++) {Auto T = std::thread (&task, i); Worke Rs.push_back (Std::move (t));} Std::cout << "Main thread" << Std::endl;std::for_each (Workers.begin (), Workers.end (), [] (Std::thread & T) {assert (t.joinable ()); T.join ();}); return 0;}
The result of the operation is:
Worker:worker:02
Worker:3
Worker:1
Main thread
Worker:4
2. Change the parameters of a thread function to a reference by referring to the pass-through thread parameter
void task (int &i) {std::cout << "worker:" << i << "\ n";}
At the same time, the constructor of the thread also needs to be modified accordingly
Auto T = std::thread (&task, Std::ref (i));
However, the above program may seem to work, but it is not a good design because multiple threads are using a reference to the same object at the same time.

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.