مشکل این هست که باید قبل از تغییر متغیر به اشتراک گذاشته شده در n تا thread از std::mutex استفاده کنید .
یا بجای int از std::atomic<int استفاده کنید .
به این شکل :
#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
void func(std::atomic_int_least32_t& counter)
{
for (int i = 0; i < 100; ++i) {
++counter;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
int main()
{
std::atomic_int_least32_t counter(0);
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i) {
threads.push_back(std::thread{ func, std::ref(counter) });
}
for (auto& t : threads) {
t.join();
}
std::cout << "Result = " << counter << std::endl;
return 0;
}