One, multi-process and multi-threading comparison
Multi-process: More than one process, the overhead is relatively large, the communication method is more complex (can use pipelines, files, Message Queuing to communicate), maintenance costs are not high.
Multithreading: The use of shared memory to carry out instruction execution, the cost is relatively low, but the maintenance is more cumbersome, need to consider the issue of shared resources. Distributed operations are not supported.
Second, multithreading example
#include"iostream.h"#include"thread.h"using namespacestd;voidfunction () {cout<<"Hello World"<<end;}intMain () {Std::thread T (function);//within T () is the method to be executed on this threadT.join ();//T joins the main thread, the main thread waits for him to execute before executing//T.detach (); //concurrent execution, which executes concurrently with the main thread, may cause the main thread to finish executing it//There is no chance of execution, and the detach cannot be in the join, unless the addition of judgment into the next/*if (t.joinable ()) {T.join ();}*/ return NULL;}
Three, multithreading management
1.
voidfunction () { for(intI=0,i<Ten; i++) {cout<<"form t,i love u"; }}intmain () {Thread T (function ()));//another way to thread executionTry{ for(intI=0,i<Ten; i++) {cout<<"form main,i love u"; }}Catch(...) {T.join ();Throw;//ensure that T and main have an execution}}
2, the thread can only be move and cannot be copied, the thread may perform all the structures that can be called (including classes, etc.)
CALSS factor{voidfunctionstringstr) {cout<<"Hello"+str<<Endl;}}voidMain () {strings="u"; thread T ((function ()), s);} If the parameter is passed by reference; CALSS factor{voidfunctionstring&str) {cout<<"Hello"+str<<Endl;}} The corresponding invocation part should be: Thread T ((function ()), std::ref(s)); If the call is: Thread T ((function ()), s), although the invoked method is a reference to pass the value, but does not affect the value of the delivery of the real, the concept of a reference is an alias, you can reduce unnecessary replication; References can also be written as Thread T ( function ()), move (s)), but the thread can only be written as a move such as: Thread T2=move (t);
3, each thread has a unique thread ID, can be obtained with get_id ();
4, each task can use how many threads to complete the operation efficiently, and the CPU core number, too much will lead to inefficient;
Thread::hardware_concurrency () View up to how much more appropriate
Multithreading and multi-process for C + +