Hello, I'm starting to deal with multithreading once again ... I found a simple example for clarity of access out of sync, but I don’t understand some things:
struct Counter { int value; Counter() : value(0){} void increment(){ ++value; } }; int main() { Counter counter; std::vector<std::thread> threads; for(int i = 0; i < 5; ++i){ threads.push_back(std::thread([&counter](){ for(int i = 0; i < 100; ++i){ counter.increment(); } })); } for(auto& thread : threads){ thread.join(); } std::cout << counter.value << std::endl; return 0; }
I absolutely can’t understand why different values fly out ... we have join () ie we wait for each of the five threads to execute one after the other (that is, increment 100 times each), I understand that if detach () stood, it would be tin ... and so each of the five streams one after another after all go ... why values other than 500 are obtained. either I don’t take something into account ... isn't it true that there will be 100 in the first stream, and there will be 100 more in the next?
++value
really increases a variable in some memory area, I have bad news for you. - VladD