一、多進程和多線程對比
多進程:進程不止一個,開銷比較大,通信方式比較復雜(可以用過管道、文件、消息隊列進行通信),維護成本不高。
多線程:利用共享內存的方式進行指令的執行,開銷比較低,但是維護起來比較麻煩,需要考慮到共享資源的問題。不支持分布式運算。
二、多線程舉例
#include "iostream.h" #include "thread.h" using namespace std; void function() { cout<<"hello world"<<end; } int main() { std::thread t(function); //t()內為要在此線程執行的方法 t.join(); //t加入主線程,主線程等待他執行完畢再執行 //t.detach(); //並發執行,和主線程同時執行,可能導致主線程執行完畢它 // 沒有機會執行,並且被detach的不能在join,除非加判斷入下 /* if(t.joinable()) { t.join(); }*/ return null; }
三、多線程管理
1、
void function() { for(int i=0,i<10;i++) { cout<<"form t,i love u"; } } int main() { thread t((function()));//線程執行的另一種方式 try { for(int i=0,i<10;i++) { cout<<"form main,i love u"; } } catch(...) { t.join(); throw; //保證t和main有一個執行 } }
2、線程只能被move而不能被復制,線程可以執行一切可以被調用的結構(包括類等)
calss factor { void function(string str) { cout<<"hello"+str<<endl; } } void main() { string s="u"; thread t((function()),s); } 如果是通過引用傳遞參數; calss factor { void function(string& str) { cout<<"hello"+str<<endl; } } 相應的調用部分應該是: thread t((function()),std::ref(s)); 如果調用的時候是: thread t((function()),s); 盡管被調用的方法是引用傳遞值的,但是並不會影響值傳遞之實; 引用就是別名的概念,可以減少不必要的復制; 引用還可以寫成 thread t((function()),move(s)); 但是線程只能寫成move 如: thread t2=move(t);
3、每個線程具有唯一的線程Id,可以用get_id()獲取;
4、每個任務可以用多少個線程高效完成操作,和cpu的核心數有關,過多反而會導致效率低;
thread::hardware_concurrency() 查看最多多少比較合適
