Threads cannot be copied, but can be transferred. In C + +, Std::ifstream cannot be copied, but can be transferred (moveable), std::thread the same.
void Some_function (); void Some_other_funciton (); Std::thread T1 (some_function);//Create Thread T1, run Some_functionstd::thread T2=std::move (t1);//create t2,t1 All rights to T2, at which point T1 is not and runs thread-related t1=std::thread (Some_other_funciton);//Create new thread, and T1 Association. Std::thread T3;t3=std::move (T2);//control is given to T3t1=std::move (T3);//control is given to T1, then T1 running thread ends
function return value is thread
Std::thread f () {void some_function (); return Std::thread (some_function);} Std::thread g () {void some_other_function (int); Std::thread t (some_other_function,42); return t;}
If the parameter of a function is a thread, it can only receive value passing.
void f (Std::thread t) {void some_funtion (); F (Std::thread (some_function)); Std::thread T (some_function); F (Std::move (t ));}
One use of the transfer of object control is to use the Thread_guard object to manage the declaration period (RAII) of the thread object. Gets control of the thread object when the Thread_guard object is created, and calls the join waiting thread in its destructor. The thread object does not allow copying and copying, so only Thread_guard has control over it and waits for the end of the thread when the Thread_guard object is destroyed. Use a class Scoped_thread to represent:
Class Scoped_thread{std::thread t;public:explicit Scoped_thread (std::thread t_) T (Std::move (T_) {if (!t.joinable ()) Throw Std::logic_error ("No thread");} ~scoped_thread () {//destructor calls join, waits for thread to end T.join ();} Disable the following two functions Scoped_thread (Scoped_thread const&) =delete;scoped_thread * operator= (scoped_thread const &) = Delete;} ; struct Func;void f () {int some_local_state;//passed the newly created thread directly, without a named variable Scoped_thread t (Std::thread (func (some_local_state)) );d o_something_in_current_thread ();}
The transfer of thread control makes it possible to use the Thread object container. The following code indicates that multiple threads are created and wait for them to end.
void do_work (unsigned id), void f () {std::vector<std::thread> threads;for (unsigned i=0;i<20;++i) { Threads.push_back (Std::thread (Do_work,i));} Call Joinstd::for_each (Threads.begin (), Threads.end (), STD::MEM_FN (&std::thread::join) on each thread;}
To transfer ownership of a thread