C++11中线程所有权转移分析
移動特性說明
C++標(biāo)準(zhǔn)庫中有很多資源占有(resource-owning)類型,比如std::ifstream,std::unique_ptr還有std::thread都是可移動,但不可拷貝。
移動拷貝或者移動賦值都使得原有對象對所屬資源的控制權(quán)發(fā)生轉(zhuǎn)移,從對象A轉(zhuǎn)移到對象B,對資源的控制只在對象B中保留。
以下是std::thread線程類的移動特性的聲明,支持移動構(gòu)造和移動對象,但不可拷貝。
//移動構(gòu)造函數(shù) thread( thread&& other ) noexcept;//移動對象 thread& operator=( thread&& other ) noexcept;//復(fù)制構(gòu)造函數(shù)被刪除 thread(const thread&) = delete;以下兩種情形都將發(fā)生線程類對象的移動操作,例如:
//返回thread參數(shù) std::thread get_thread() {//方式一://return std::thread (do_fun, 100);//方式二:std::thread td(do_fun, 100);return td; }//傳遞thread參數(shù) void move_thread(std::thread td) { }在C++ 11中標(biāo)準(zhǔn)庫中,提供了std::move函數(shù)用于資源移動操作,這個一般應(yīng)用于命名類對象std::thread td1,其函數(shù)聲明如下:
template< class T > typename std::remove_reference<T>::type&& move( T&& t ) noexcept;std::move 用于指示對象 t 可以“被移動”,即允許從 t 到另一對象的有效率的資源傳遞。
線程移動操作變化說明
當(dāng)一個std::thread對象執(zhí)行移動操作后,線程的所有權(quán)將發(fā)生轉(zhuǎn)移,原有線程對象的相關(guān)標(biāo)識被清空,失去線程的控制權(quán)。其原有線程類對象ID變?yōu)?,joinable變?yōu)闉閒alse。
代碼說明如下:
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;//發(fā)生移動操作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, 調(diào)用join 程序異常,//移動后task對象的joinable為falseif (task.joinable()){task.join();std::cout << "call task member function " << std::endl;}//如果joinable為false, 調(diào)用join 程序異常if (move_task.joinable()){move_task.join();std::cout << "call move_task member function " << std::endl;} }?運(yùn)行結(jié)果:
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下面就利用線程的移動特性,進(jìn)行量產(chǎn)線程,并等待它們結(jié)束。
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)); // 產(chǎn)生線程}std::for_each(threads.begin(),threads.end(),std::mem_fn(&std::thread::join)); // 對每個線程調(diào)用join() }本文轉(zhuǎn)自:C++11中線程所有權(quán)轉(zhuǎn)移分析_Keep Moving~-CSDN博客_c 線程轉(zhuǎn)移
總結(jié)
以上是生活随笔為你收集整理的C++11中线程所有权转移分析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为在巴塞罗那斩获十项行业技术大奖 实在
- 下一篇: 年轻人越来越离不开B站了:日均使用96分