Why is this not thread-safe?
From my understanding, the result should be a string of 100
s.
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
int main()
{
std::vector<int*> values(100, new int(0));
std::vector<std::thread> threads;
std::vector<std::mutex> mutexes(100);
for (int i = 0; i < 100; i++)
{
threads.emplace_back([](int* v, std::mutex* m)
{
for (int j = 0; j < 100; j++)
{
std::lock_guard<std::mutex> guard(*m);
(*v)++;
}
}, values[i], &mutexes[i]);
}
for (auto& t : threads) t.join();
for (int i = 0; i < 100; i++)
{
std::lock_guard<std::mutex> guard(mutexes[i]);
std::cout << (*(values[i])) << ' ';
}
std::cout << std::endl;
}
Result:
9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863
question from:
https://stackoverflow.com/questions/65933150/why-is-this-not-thread-safe 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…