当std :: thread被破坏时,如果指针指向它,那么shared_ptr会发生什么?

时间:2017-06-12 17:32:27

标签: c++ multithreading shared-ptr stdthread

当我创建一个std :: thread实例时,它什么时候会被破坏?是线程完成任务然后被破坏的时间还是作为普通对象的时间,当它不再被使用时将被破坏?

//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()之后线程对象是否被破坏?

2 个答案:

答案 0 :(得分:3)

  

threadPtr->join()之后线程对象是否被破坏?

没有。 join()结束std::thread对象表示的执行线程,它不会销毁std::thread对象。

  

当我创建一个std :: thread实例时,它什么时候会被破坏?

threadPtr超出范围时,它将被销毁,因为它是一个自动对象(它有automatic storage duration)。 std::shared_ptr析构函数将调用std::thread析构函数,然后释放它获得的内存。

答案 1 :(得分: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通常是包装类(或代理设计模式)的实现。它包含对通常是操作系统线程对象的(可能为空)引用。当包裹的线程结束时,引用可以为空。