c++ - 从另一个线程调用 shared_from_this 但在初始化 shared_ptr 之后获取 bad_weak_ptr

标签 c++ multithreading stl shared-ptr

<分区>

p->start() 被调用之后 - shared_from_this 抛出 bad_weak_ptr
但如您所见,p->start()shared_ptr 完全启动后调用。

struct A : std::enable_shared_from_this<A> 
{
    std::thread* t = nullptr;
    A() {}
    ~A(){ 
        t->join(); 
        delete t; 
    }
    void f() { 
        try{
            auto p = this->shared_from_this(); 
            std::cout << "p:" << p.get() << "\n";
        } catch(...) { 
            std::cout << "Exception !!!\n"; 
        }
    }
    void start() { 
        t = new std::thread(&A::f,this); 
    }
};
std::shared_ptr<A> create() { 
    A* a = new A();
    std::shared_ptr<A> p(a);
    p->start();
    return p;
}
int main()
{   
    int i = 0;
    std::map<int,std::shared_ptr<A>> map;
    while( i < 1024) { 
        auto ptr = create();
        map[i++] = ptr;
    } 
    return 0;
}

link to working code (coliru) - unexplained bad_weak_ptr - exception is thrown ...

最佳答案

你的问题是你在 join 上有竞争条件。 main 可能正在退出,破坏 map 中的对象。映射中的 shared_ptr 被销毁,调用你的对象的析构函数想要加入,但为时已晚: enable_shared_from_this 想要使用的 shared_ptr是 toast 。然后(竞争条件)在对象自己的线程中,它尝试从死的 weak_ptr 上获取共享,这会导致抛出异常并在 cout 上打印消息。

关于c++ - 从另一个线程调用 shared_from_this 但在初始化 shared_ptr 之后获取 bad_weak_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42237009/

相关文章:

c++ - 使用 std::make_shared() 的数据缓存影响

c++ - 模板函数中任意迭代器的值类型

c++ - 通过索引获取 C++ std::set 的成员

c++ - gsl::not_null<T*> 与 std::reference_wrapper<T> 与 T&

multithreading - 使用多线程处理硬盘驱动器上的文件有用吗?

c++ - 如何在 MFC 功能区应用程序中使用自动完成编辑控件

c++ - 在 C++11 中,使用 std::unique_lock<std::mutex> 作为类成员是否明智(甚至安全)?如果是这样,是否有任何指导方针?

Java 客户端/服务器聊天

C++串口问题

c++ - equal_range 应该如何工作?