簡體   English   中英

如果我在多線程中重置相同的 shared_ptr 不會崩潰

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

我只想確認在多線程中使用鎖定重置為相同的智能指針是安全的嗎? 如果沒有lock_guard,它不安全,因為它不是線程安全的方法? 我想重置不是線程安全的,但是,如果我刪除了鎖,則不會觀察到崩潰。

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;
}

shared_ptr對象不是線程安全的,指向的對象也不是線程安全的。 只有引用計數是線程安全的。 所以是的,你需要使用警衛。

在 C++20 中,有std::atomic<std::shared_ptr<T>>

文檔不能保證該組件的安全性。 基本上,如果標准對此一無所知,那么您的假設是正確的。 你必須有那個 lockquard 或任何提供相同功能的東西。

崩潰可能是不可觀察的,因為在嘗試在並發線程中讀取指針之前您沒有競爭條件,因為您實際上並沒有嘗試使用該值(reset 所做的只是更改指針值)。

好吧,你不能依賴於你不能觀察到 UB,UB 是一只薛定諤的貓。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM