C++11中线程所有权转移分析
生活随笔
收集整理的這篇文章主要介紹了
C++11中线程所有权转移分析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
移動特性說明
C++標準庫中有很多資源占有(resource-owning)類型,比如std::ifstream,std::unique_ptr還有std::thread都是可移動,但不可拷貝。
移動拷貝或者移動賦值都使得原有對象對所屬資源的控制權發生轉移,從對象A轉移到對象B,對資源的控制只在對象B中保留。
以下是std::thread線程類的移動特性的聲明,支持移動構造和移動對象,但不可拷貝。
//移動構造函數 thread( thread&& other ) noexcept;//移動對象 thread& operator=( thread&& other ) noexcept;//復制構造函數被刪除 thread(const thread&) = delete;以下兩種情形都將發生線程類對象的移動操作,例如:
//返回thread參數 std::thread get_thread() {//方式一://return std::thread (do_fun, 100);//方式二:std::thread td(do_fun, 100);return td; }//傳遞thread參數 void move_thread(std::thread td) { }在C++ 11中標準庫中,提供了std::move函數用于資源移動操作,這個一般應用于命名類對象std::thread td1,其函數聲明如下:
template< class T > typename std::remove_reference<T>::type&& move( T&& t ) noexcept;std::move 用于指示對象 t 可以“被移動”,即允許從 t 到另一對象的有效率的資源傳遞。
線程移動操作變化說明
當一個std::thread對象執行移動操作后,線程的所有權將發生轉移,原有線程對象的相關標識被清空,失去線程的控制權。其原有線程類對象ID變為0,joinable變為為false。
代碼說明如下:
void do_fun(int num) {++num; }int _tmain(int argc, _TCHAR* argv[]) {int num = 10;//原有對象std::thread task(do_fun, num);std::cout << "before call move task thread id is " << task.get_id() << std::endl;std::cout << "before call move task thread joinable status is " << task.joinable() << std::endl;//發生移動操作std::thread move_task = std::move(task);std::cout << "\nafter call move task thread id is " << task.get_id() << std::endl;std::cout << "after call move task thread joinable status is " << task.joinable() << std::endl;std::cout << "\nmove_task thread id is " << move_task.get_id() << std::endl;std::cout << "move_task thread joinable status is " << move_task.joinable() << std::endl;//如果joinable為false, 調用join 程序異常,//移動后task對象的joinable為falseif (task.joinable()){task.join();std::cout << "call task member function " << std::endl;}//如果joinable為false, 調用join 程序異常if (move_task.joinable()){move_task.join();std::cout << "call move_task member function " << std::endl;} }?運行結果:
before call move task thread id is 17512 before call move task thread joinable status is 1after call move task thread id is 0 after call move task thread joinable status is 0move_task thread id is 17512 move_task thread joinable status is 1 call move_task member function下面就利用線程的移動特性,進行量產線程,并等待它們結束。
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)); // 產生線程}std::for_each(threads.begin(),threads.end(),std::mem_fn(&std::thread::join)); // 對每個線程調用join() }本文轉自:C++11中線程所有權轉移分析_Keep Moving~-CSDN博客_c 線程轉移
總結
以上是生活随笔為你收集整理的C++11中线程所有权转移分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为在巴塞罗那斩获十项行业技术大奖 实在
- 下一篇: 年轻人越来越离不开B站了:日均使用96分