简体   繁体   中英

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? 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. 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>> .

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.

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).

Well and you can't rely on that you can't observe an UB, UB is a Schrodinger's cat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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