C++11併發學習之二:執行緒管理
1.啟動執行緒
(1)使用物件
“小試牛刀”中thread構造時傳入的是函式,還可以傳入物件。
#include <thread> #include <iostream> void func() { std::cout<<"worker thread ID:"<<std::this_thread::get_id()<<std::endl; std::cout<<"Hello Word"<<std::endl; } class MyFunc { public: //過載的函式操作符,物件使用起來就像物件是一個函式一樣 void operator()()//無引數無返回值 { func(); } }; int main() { std::cout<<"main thread ID:"<<std::this_thread::get_id()<<std::endl; MyFunc myFunc;//需先定義類的物件 std::thread workerThread(myFunc); workerThread.join(); return 0; }
(2)使用引數 #include <thread> #include <iostream> #include <string> void func(int i,std::string const &s) { std::cout<<"worker thread ID:"<<std::this_thread::get_id()<<std::endl; std::cout<<"Hello Word"<<" "<<s<<" "<<i<<std::endl; } int main() { std::cout<<"main thread ID:"<<std::this_thread::get_id()<<std::endl; std::string str="at"; //注意這裡第二個引數的寫法 //為何不直接傳str:雖然函式func的第二個引數期待傳入一個引用,但是std::thread得建構函式 //並不知曉;建構函式無視函式期待的資料型別,並盲目的拷貝已提供的變數。當執行緒呼叫func函式 //時,傳遞給函式的引數是str變數內部拷貝的引用,而非資料本身的引用。使用std::ref可以解決 //這個問題,將引數轉換成引用的形式。 std::thread workerThread(func,20161016,std::ref(str)); workerThread.join(); return 0; }
(3)使用move #include <thread> #include <iostream> #include <string> void func(int i,std::string const &s) { std::cout<<"worker thread ID:"<<std::this_thread::get_id()<<std::endl; std::cout<<"Hello Word"<<" "<<s<<" "<<i<<std::endl; } void func_other(int i,std::string const &s) { std::cout<<"worker thread ID:"<<std::this_thread::get_id()<<std::endl; std::cout<<"C++11"<<" "<<s<<" "<<i<<std::endl; } int main() { std::cout<<"main thread ID:"<<std::this_thread::get_id()<<std::endl; std::string str="at"; std::thread workerThread1(func,20161016,std::ref(str)); std::thread workerThread2=std::move(workerThread1); workerThread1=std::thread(func_other,20161016,std::ref(str)); std::thread workerThread3; std::thread workerThread4; //此句崩潰,workerThread4並未啟動 // workerThread4.join(); workerThread3=std::move(workerThread2); //此句崩潰,因為workerThread1已經關聯一個執行緒 // workerThread1=std::move(workerThread3); workerThread1.join(); //此句崩潰,因為workerThread2沒有關聯一個執行緒 // workerThread2.join(); workerThread3.join(); return 0; }
2.後臺執行執行緒 #include <thread> #include <iostream> #include <string> #include <chrono> #include <assert.h> void func(int i,std::string const &s) { std::cout<<"worker thread ID:"<<std::this_thread::get_id()<<std::endl; std::cout<<"Hello Word"<<" "<<s<<" "<<i<<std::endl; } int main() { std::cout<<"main thread ID:"<<std::this_thread::get_id()<<std::endl; std::string str="at"; std::thread workerThread(func,20161016,std::ref(str)); //使用detach()會讓執行緒在後臺執行,也就是說主執行緒不會等待workerThread結束。如果執行緒detach(), //不可能有std::thread物件能引用它,而且不能再呼叫該執行緒的join()方法。 workerThread.detach(); //workerThread.joinable()為false assert(!workerThread.joinable()); //延時10秒,否則然函式func函式還未執行,man函式就退出了 std::this_thread::sleep_for(std::chrono::seconds(10)); return 0; }
--------------------- 作者:燦哥哥 來源:CSDN 原文:https://blog.csdn.net/caoshangpa/article/details/52831290?utm_source=copy 版權宣告:本文為博主原創文章,轉載請附上博文連結!