我只是在做一个多线程/并发教程,下面的代码(我认为)应该不能正常工作,因为 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;
}