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.