![](/img/trans.png)
[英]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.