2017-06-12 1 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

'threadPtr'は、他のスタック変数と同じようにmainを離れるときに破壊されます。 – stark

答えて

3

threadPtr->join()の後にスレッドオブジェクトが破壊されていますか?

join()std::threadオブジェクトが表す実行のスレッドを終了し、それがstd::threadオブジェクトを破壊しません。

私はstd :: threadインスタンスを作成すると、いつ破壊されますか?

、自動オブジェクト(それはautomatic storage durationを有する)であるのでthreadPtrがスコープの外に出るときに破壊されます。 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は、通常、ラッパークラス(またはプロキシデザインパターン)の実装です。通常、オペレーティングシステムのスレッドオブジェクトとは何か(おそらく空の)参照を含みます。ラップされたスレッドが終了すると、参照が空になることがあります。

関連する問題