[問題] 關於互斥的問題
開發平台(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
推
06/11 22:32,
5年前
, 1F
06/11 22:32, 1F
→
06/12 07:53,
5年前
, 2F
06/12 07:53, 2F
→
06/12 07:53,
5年前
, 3F
06/12 07:53, 3F
→
06/12 07:53,
5年前
, 4F
06/12 07:53, 4F
→
06/12 07:53,
5年前
, 5F
06/12 07:53, 5F
推
06/13 00:28,
5年前
, 6F
06/13 00:28, 6F
推
06/13 00:42,
5年前
, 7F
06/13 00:42, 7F
謝謝前輩的建議 最後我的get set 函式改成存取std::map的資料型態 且有作std::mutex
※ 編輯: asdfg1597860 (114.40.196.68 臺灣), 06/13/2020 22:53:32
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章