1. Basic Introduction
In c++11, threads are started by Std::thread objects, using the
// header files that must be included void do_work () { std::cout<<"HelloWorld"; } int Main () { std::thread my_thread (do_work);}
This opens a new thread and runs the Do_work function.
Note that when a temporary and unnamed variable is passed to the thread constructor, the new method is used as follows
#include"Thread"voidHello () {std::cout<< std::this_thread::get_id () <<Std::endl;}classa{ Public: void operator() ()Const{Hello (); }};intMainintargcChar*argv[]) {std::thread t{A ()};//or Std::thread t ((A ()));Std::cout << std::this_thread::get_id () <<Std::endl; System ("Pause");} Will output two thread IDs
The above code executes the Hello function in the new thread, where the class name is followed by a parenthesis called an anonymous object, which constructs an object by default, but the object exists only in the line of code that constructs the object, and immediately after the line of code that constructs the anonymous object, the destructor is called, as
class a{public: A () { "a"; }}; int Main (intChar *argv[]) { A (); System ("pause");} // This will output a
And this anonymous object is treated as a function rather than an object as a std::thread argument, so use the special method described above
To pass parameters to a thread, use the method
void f (int i,int d); void Fun () { std::thread T (F,1,ten);}
Here 1 is the parameter i,10 is the parameter d. Also note that the function called when the parameter is passed will blindly copy the parameters of the incoming zone instead of the original value, and if you do not want to invoke replication using the original value, use Std::thread t (f,std::ref (1), 10) to
2. Thread Management
Once the thread is started, you need to explicitly decide whether to wait for it to finish or let it run itself, for C++11, two ways to use Jion (), detach (), and if you do not make a decision before the Std::thread object is destroyed, your program will be at std:: The thread's destructor call Std::terminate () terminates.
If you choose to detach, the thread may still be running long after the Std::thread object is destroyed, in which case it is important to guard against invoking an object that might have been destroyed before the end of the thread
Call Join (), the main thread will always be there waiting for the new thread to execute before it continues to execute. You can only call join () or detach () to a given thread once, and you may use joinable () to determine
C++11 multi-line assigns feature learning (1) Managing Threads