I am new to threading and I wrote a simple thread program to see how it works in C++.
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
using namespace std::chrono;
void funcSum(long long int start, long long end)
{
long long int sum = 0;
for(auto i = start; i <= end; ++i)
{
sum += i;
}
cout << sum;
}
int main()
{
auto startTime = high_resolution_clock::now();
long long int start = 0, end = 90000;
thread t1(funcSum, start, end);
t1.join();
funcSum(start, end);
auto stopTime = high_resolution_clock::now();
auto duration = duration_cast<seconds>(startTime - stopTime);
cout << "\n" << duration.count() << " Seconds\n";
return 0;
}
The above code produces some random output: 40500450004050045000 0 Seconds
What is wrong in this code? Why I am getting a random garbage number? I am expecting it to print only the sum of numbers from 0 to 90000.