2017-06-12 63 views
-1

當我創建一個std :: thread實例時,它何時會被破壞?是線程完成它的任務的時間,然後它被破壞了,或者它作爲一個普通對象工作,當它不再被使用時它會被破壞。當std :: thread被銷燬時,如果指針指向shared_ptr會發生什麼?

//a fake function for std::thread 
void func(); 
void main() 
{ 
    auto threadPtr = std::make_shared<std::thread>(func) 
    threadPtr->join(); 
    // is thread object which threadPtr point destructed in here ? 
    //... other stuffs ....  
} 

線程對象被破壞後threadPtr->join()

+0

沒有其他代碼共享那個線程實例,所以如果它簡單地分配在堆棧上,它將僅僅是相同的。 –

+1

你爲什麼認爲線程對象被破壞了? – NathanOliver

+0

當你離開main時,'threadPtr'被銷燬,就像任何其他堆棧變量一樣。 – stark

回答

3

線程對象被破壞後threadPtr->join()

join()結束執行線程,所述std::thread對象表示,它不破壞std::thread對象。

當我創建一個std :: thread實例時,它何時會被破壞?

threadPtr由於是自動對象(它有automatic storage duration)而超出範圍時它將被銷燬。 std::shared_ptr析構函數將調用std::thread析構函數,然後釋放它獲得的內存。

1

底層操作系統線程可能已終止,但與正在銷燬的C++ std::thread對象不同。

執行以下:

#include <iostream> 
#include <thread> 
#include <mutex> 
#include <atomic> 

std::mutex cout_mutex; 
std::atomic<bool> waiter{true}; 

void func(){ 
    { 
     std::lock_guard<std::mutex> guard(cout_mutex); 
     std::cout << "funky\n"; 
    } 
    while(waiter);//cheap spin waiting... 
} 

int main() { 

    auto threadPtr = std::make_shared<std::thread>(func); 
    { 
     std::lock_guard<std::mutex> guard(cout_mutex); 
     std::cout << "an active thread id: "<<threadPtr->get_id()<<'\n'; 
    } 
    waiter=false; 
    threadPtr->join(); 
    std::cout << "terminated thread id: "<< threadPtr->get_id()<<'\n'; 
    return 0; 
} 

輸出變化,但是可能的輸出這裏是:

an active thread id: 47441922455296 
funky 
terminated thread id: thread::id of a non-executing thread 

中包含的對象threadptr保持有效直到破壞,而是可以參照一個封端的螺紋。

std::thread通常是包裝類(或代理設計模式)的實現。它包含(通常爲操作系統線程對象的(可能爲空)引用。當包裹的線程結束時,引用可能會變空。

相關問題