[英]Why does this produce correct output?
I was just working on a multithreading/concurrency tutorial, and the following code (I think) is supposed to not work correctly, because 5 different threads operate on the same object. 我只是在编写多线程/并发教程,下面的代码(我认为)应该无法正常工作,因为5个不同的线程在同一个对象上运行。
But it prints out exactly 500 every time. 但是,每次都精确打印出500张。 How does that work?
这是如何运作的? I'm not using mutexes, so there is no protection against accessing the same data by multiple threads...
我没有使用互斥锁,因此无法防止多个线程访问相同的数据...
#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;
}
Depending on the compiler, the increment ++i
will result in a single instruction, which means that the increment will likely be performed atomically. 根据编译器的不同,增量
++i
将导致一条指令,这意味着该增量可能会自动执行。
However, execution still results in a data race when multiple threads write to the same memory without any form of synchronization and will lead to undefined behaviour . 但是,当多个线程在没有任何形式的同步的情况下写入同一内存时,执行仍然会导致数据争用,并且将导致不确定的行为 。 UB means that just about anything can happen, including showing the correct answer.
UB意味着几乎所有事情都会发生,包括显示正确答案。
Multi-Threaded processing can be a strange beast as Snps said, i think you add a few print statements to your so you can detect how it is behaving while its running. 正如Snps所说,多线程处理可能是一个奇怪的野兽,我想您在其中添加了一些打印语句,以便可以在运行时检测它的行为。 I normally do that when i run into something confusing with any thing threaded.
当我碰到任何与线程混淆的东西时,我通常会这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.