看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) Win10 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) VS2015 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 各位前輩好 小弟我有一個問題想問 如果我有一個類別 裡面有一個變數及2個函式(1個取變數的值,1個改變變數的值) 用兩個thread 去跑這兩個函示 ,會有機率造成資源互搶嗎?(再寫值時被取值的狀況) 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) Class A { public: int get(); void update(int input); private: int value; } int A::get() { return value; } void A::update(int input) { value = input; } 補充說明(Supplement): 類別的結構在上方 主程式會有全域的類別物件 A itemA; 然後開兩條Thread ,一條呼叫itemA.update(亂數) ,一條呼叫itemA.get() 想請問前輩們,這狀況下有可能會資源互搶嗎 目前測試是沒有發生 但感覺時間拉長可能會有機率 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 218.173.147.157 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1591884322.A.475.html
ucrxzero: lock 再wait 還會嗎 06/11 22:32
Lipraxde: 會,不過 int 太小了所以在 x86 上這樣應該觀察不出來 06/12 07:53
Lipraxde: 印象中 x86 在 read/write 對齊的 word 時是 atomic 的 06/12 07:53
Lipraxde: 即使是如此 lock 也是無法取代的,因為 lock 的實作需 06/12 07:53
Lipraxde: 要 read modify write 06/12 07:53
FY4: 用mutex保護吧 06/13 00:28
icetofux: 用std::atomic包裝你的變數應該能解決這個問題 06/13 00:42
謝謝前輩的建議 最後我的get set 函式改成存取std::map的資料型態 且有作std::mutex ※ 編輯: asdfg1597860 (114.40.196.68 臺灣), 06/13/2020 22:53:32