简体   繁体   English

如果我在多线程中重置相同的 shared_ptr 不会崩溃

[英]no crash if I reset the same shared_ptr in multi-threads

I just want to confirm it's safe to reset to the same smart pointer with lock in multi-threads?我只想确认在多线程中使用锁定重置为相同的智能指针是安全的吗? if there is no lock_guard, it's not safe due to it is not a thread-safe method?如果没有lock_guard,它不安全,因为它不是线程安全的方法? I suppose reset is not threadsafe, however, no crash is observed if I removed the lock.我想重置不是线程安全的,但是,如果我删除了锁,则不会观察到崩溃。

class foo {
public:
   foo()
   {
       std::cout << "foo constructed" << std::endl;
   }
   ~foo()
   {
       std::cout << "foo destructed" << std::endl;
   }
};
int main(int argc, const char * argv[]) {
    std::shared_ptr<foo> f = std::make_shared<foo>();
    conqueue = dispatch_queue_create("MyConcurrentDiapatchQueue", DISPATCH_QUEUE_CONCURRENT);
    static std::mutex io_mutex;
    for (int i = 0; i < 100000; i++)
    {
        dispatch_async(conqueue, ^{

            std::lock_guard<std::mutex> lk(io_mutex); // no crash without this line as well
            f.reset(); // it's safe? No crash if I reset the same shared_ptr in multi-threads.
        });
    }
    return 0;
}

The shared_ptr object is not thread-safe, nor is the pointed-to object. shared_ptr对象不是线程安全的,指向的对象也不是线程安全的。 Only the reference count is thread-safe.只有引用计数是线程安全的。 So yes, you need to use a guard.所以是的,你需要使用警卫。

In C++20, there is std::atomic<std::shared_ptr<T>> .在 C++20 中,有std::atomic<std::shared_ptr<T>>

Documentation don't guarantee safety of that component.文档不能保证该组件的安全性。 Essentially if standard says nothing about it then your assumption is right.基本上,如果标准对此一无所知,那么您的假设是正确的。 You have to have that lockquard or anything that provides same functionality.你必须有那个 lockquard 或任何提供相同功能的东西。

Crash might be no observable because you don't have racing condition until you try read pointer in a concurrent thread because you don't actually try to use that value (all that reset does is to change pointer value).崩溃可能是不可观察的,因为在尝试在并发线程中读取指针之前您没有竞争条件,因为您实际上并没有尝试使用该值(reset 所做的只是更改指针值)。

Well and you can't rely on that you can't observe an UB, UB is a Schrodinger's cat.好吧,你不能依赖于你不能观察到 UB,UB 是一只薛定谔的猫。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM