I think my program has a bug because sometimes when I run my program, it outputs a lower number than 30000, such as 29999. But sometimes it runs correctly and gets to the 30000. My question is how can I fix this and why is it happening.
#include <iostream>
#include <thread>
using namespace std;
int counter;
int i;
void increment()
{
counter++;
}
int main()
{
counter = 0;
cout << "The value in counter is : " << counter << endl;
thread tarr[30000];
for (i = 0; i < 30000; i++)
{
tarr[i] = thread(increment);
}
for (i = 0; i < 30000; i++)
{
tarr[i].join(); //main thread waits for tarr to finish
}
cout << "After running 30,000 threads ";
cout << "the value in counter is : " << counter << endl;
return 0;
}