[問題] shared_ptr 是否 atomic or thread safe
這問題一直是讓我很難理解
我看了 cppreference, 他提到 你只要用了non-const method的話就不thread safe
問題出在
https://en.cppreference.com/w/cpp/memory/shared_ptr/operator%3D
這不是non-const , 而我看到的程式碼(也許早就寫錯了)
我並沒有看到mutex or 一些保護機制去保護shared_ptr assignment
假設一個情況
Thread1
mSp = nullptr; 內部應該是refcount--; 假設剛好歸零 想要開始delete 內部rawptr
這時剛好context switch到Thread2
Thread2
mSp = mOtherSp; 這時內部rawptr = otherrawptr已經做完了
refcount也++了 剛好又context switch回Thread1
然後delete rawptr就執行了
以上這個情況是不是有機會發生? 但如果有, 是不是變成shared_ptr本身只要
被multithread用就必須也要用mutex來保護(畢竟不可能只操作const method)?
因為沒看過這樣寫的程式碼 懷疑自己是不是理解錯誤
而且如果這樣 shared_ptr裡面的refcount也沒必要用atomic了吧?
整件事都交給使用者自己做好thread safe,
我不太理解只有refcount atomic的用意是什麼. 是不是有什麼根本上的原因才這樣設計
謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 218.255.89.17 (香港)
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1562900811.A.014.html
推
07/12 12:20,
6年前
, 1F
07/12 12:20, 1F
→
07/12 13:56,
6年前
, 2F
07/12 13:56, 2F
→
07/12 13:58,
6年前
, 3F
07/12 13:58, 3F
→
07/12 13:59,
6年前
, 4F
07/12 13:59, 4F
→
07/12 18:42,
6年前
, 5F
07/12 18:42, 5F
→
07/12 19:10,
6年前
, 6F
07/12 19:10, 6F
→
07/12 19:10,
6年前
, 7F
07/12 19:10, 7F
→
07/12 19:10,
6年前
, 8F
07/12 19:10, 8F
推
07/14 11:42,
6年前
, 9F
07/14 11:42, 9F
→
07/14 11:43,
6年前
, 10F
07/14 11:43, 10F
→
07/14 11:44,
6年前
, 11F
07/14 11:44, 11F
→
07/14 11:45,
6年前
, 12F
07/14 11:45, 12F
→
07/14 11:45,
6年前
, 13F
07/14 11:45, 13F
→
07/14 12:04,
6年前
, 14F
07/14 12:04, 14F
→
07/14 12:05,
6年前
, 15F
07/14 12:05, 15F
→
07/14 12:07,
6年前
, 16F
07/14 12:07, 16F