[英]Why does my program produce correct output when my vector< vector< vector<int> > > is larger than the RAM?
[英]Why does this produce correct output?
我只是在編寫多線程/並發教程,下面的代碼(我認為)應該無法正常工作,因為5個不同的線程在同一個對象上運行。
但是,每次都精確打印出500張。 這是如何運作的? 我沒有使用互斥鎖,因此無法防止多個線程訪問相同的數據...
#include <iostream>
#include <vector>
#include <thread>
using namespace std;
struct Counter {
int value;
void increment() {
value++;
}
};
int main(){
Counter counter;
counter.value = 0;
vector <thread> threads;
for (int i = 0; i < 5; i++){
threads.push_back(thread([&counter](){
for (int i = 0; i < 100; ++i){
counter.increment();
}
}));
}
for (auto& thread : threads)
thread.join();
cout << counter.value << endl;
cin.get();
return 0;
}
根據編譯器的不同,增量++i
將導致一條指令,這意味着該增量可能會自動執行。
但是,當多個線程在沒有任何形式的同步的情況下寫入同一內存時,執行仍然會導致數據爭用,並且將導致不確定的行為 。 UB意味着幾乎所有事情都會發生,包括顯示正確答案。
正如Snps所說,多線程處理可能是一個奇怪的野獸,我想您在其中添加了一些打印語句,以便可以在運行時檢測它的行為。 當我碰到任何與線程混淆的東西時,我通常會這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.