[英]C++ Is it safe to modify a int64_t when reading it from another thread?
我有 2 個線程,A 和 B。線程 A 想讓 B 知道它收到了多少條數據記錄。 在現代 C++ 中,我們可以使用 Atomic 或 CAS 或 Mutex 來修改計數器。 但是,它們對我來說都不夠快。
我很關心,使用沒有鎖的 int64_t 在線程之間共享數據計數器。 只有線程 A 可以修改它,其他線程只能讀取它。 我不知道這樣做是否安全。
我知道在 x86-64 機器中,一個 64 位 int 可以用一個 asm store
編寫。 所以我認為它應該是安全的。 我寫了下面的代碼來檢查它。 如果該方法不安全,cnt 不會總是增加,因為我們將從該 64 位 memory 讀取錯誤值。
#include <iostream>
#include <vector>
#include <thread>
using namespace std;
int main() {
int64_t cnt = 0;
vector<thread> threadVec;
for (int i=0; i<10; i++){
threadVec.emplace_back(move(thread([&cnt](){
int64_t prev = 0, tmp = 0;
while(prev != INT64_MAX){
tmp = cnt;
// If it is not safe, tmp will not increase all the time.
if (tmp < prev) cout << "Error cnt declined" << endl;
// if (tmp % 1000000 == 0) cout << tmp << endl;
prev = tmp;
}
})));
}
this_thread::sleep_for(chrono::seconds(1));
while(cnt < INT64_MAX) cnt++;
for (auto& t : threadVec)
t.join();
return 0;
}
那么這個想法正確嗎?
不,這是未定義的行為。
改為std::atomic<int64_t>
。 這就是std::atomic
的用途。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.