[問題] 關於std::mutex的應用
開發平台(Platform): (Ex: Win10, Linux, ...)
Win10/Linux
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
GCC
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
None
問題(Question):
最近在使用C++11的std::thread,我已經知道若要在不同的thread存取同一個變數,
必須使用mutex來做管理才能達到Thread-Safe。
目前遇到的問題是,若我有多個不同的變數分別必須在多個不同的thread內存取,我
除了變數名稱外,還必須一一產生對應的mutex,我想建立下列這樣的樣板類別:
template <class T>
class SharedVariable {
private:
std::mutex mtx;
T data;
public:
T Get(void) {
T data_cpy;
std::lock_guard<std::mutex> lck(mtx);
data_cpy = this->data;
return data_cpy;
}
void Set(const T data) {
std::lock_guard<std::mutex> lck(mtx);
this->data = data;
}
};
在產生變數物件的同時,該物件也同時具有一個不用額外命名的mutex,並且當我
透過Get/Set存取變數時,也自動做好了上鎖、解鎖的功能。
SharedVariable<int> shared_int;
SharedVariable<std::string> shared_string;
SharedVariable<std::vector<double>> shared_vector;
shared_int.Set(123);
int a = shared_int.Get();
目前比較讓我有疑慮的是,在不同的thread內使用物件本身(如上例的shared_int、
shared_string、shared_vector)是一個Thread-Safe的行為嗎?我不確定要如何判
斷,想請有經驗的先進指教。
謝謝。
餵入的資料(Input):
None
預期的正確結果(Expected Output):
None
錯誤結果(Wrong Output):
None
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
None
補充說明(Supplement):
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.169.91.49 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1587997603.A.BCE.html
→
04/27 23:43,
5年前
, 1F
04/27 23:43, 1F
→
04/27 23:43,
5年前
, 2F
04/27 23:43, 2F
→
04/27 23:43,
5年前
, 3F
04/27 23:43, 3F
→
04/28 07:45,
5年前
, 4F
04/28 07:45, 4F
→
04/28 07:45,
5年前
, 5F
04/28 07:45, 5F
→
04/28 07:45,
5年前
, 6F
04/28 07:45, 6F
→
04/28 07:45,
5年前
, 7F
04/28 07:45, 7F
→
04/28 09:01,
5年前
, 8F
04/28 09:01, 8F
→
04/28 09:01,
5年前
, 9F
04/28 09:01, 9F
→
04/28 09:01,
5年前
, 10F
04/28 09:01, 10F
推
04/28 09:47,
5年前
, 11F
04/28 09:47, 11F
以我對atomic的認識,似乎只有幾種基本型態有提供atomic,我不是很確定像是string或是vector能不能使用。
→
04/28 11:56,
5年前
, 12F
04/28 11:56, 12F
→
04/28 11:56,
5年前
, 13F
04/28 11:56, 13F
→
04/28 11:56,
5年前
, 14F
04/28 11:56, 14F
→
04/28 11:59,
5年前
, 15F
04/28 11:59, 15F
→
04/28 12:00,
5年前
, 16F
04/28 12:00, 16F
※ 編輯: icetofux (111.71.40.212 臺灣), 04/28/2020 12:52:59
→
04/28 13:53,
5年前
, 17F
04/28 13:53, 17F
→
04/28 13:54,
5年前
, 18F
04/28 13:54, 18F
推
04/28 22:55,
5年前
, 19F
04/28 22:55, 19F
→
04/29 13:37,
5年前
, 20F
04/29 13:37, 20F
→
04/29 13:38,
5年前
, 21F
04/29 13:38, 21F
→
04/29 13:38,
5年前
, 22F
04/29 13:38, 22F
→
04/29 13:38,
5年前
, 23F
04/29 13:38, 23F
→
04/29 13:40,
5年前
, 24F
04/29 13:40, 24F
→
04/29 13:41,
5年前
, 25F
04/29 13:41, 25F
推
04/29 14:04,
5年前
, 26F
04/29 14:04, 26F
→
04/29 14:04,
5年前
, 27F
04/29 14:04, 27F
→
04/29 14:04,
5年前
, 28F
04/29 14:04, 28F
→
04/29 14:04,
5年前
, 29F
04/29 14:04, 29F
推
04/30 18:11,
5年前
, 30F
04/30 18:11, 30F
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章