I want to add a series of numbers [1-->5000] with threads. But the result is not correct.
The goal is only to understand the threading well, because I am a beginner.
I tried this:
void thread_function(int i, int (*S))
{
(*S) = (*S) + i;
}
main()
{
std::vector<std::thread> vecto_Array;
int i = 0, Som = 0;
for(i = 1; i <= 5000; i++)
{
vecto_Array.emplace_back([&](){ thread_function(i, &Som); });
}
for(auto& t: vecto_Array)
{
t.join();
}
std::cout << Som << std::endl;
}
And I tried this:
int thread_function(int i)
{
return i;
}
main()
{
std::vector<std::thread> vecto_Array;
int i = 0, Som = 0;
for(i = 1; i <= 5000; i++)
{
vecto_Array.emplace_back([&](){ Som = Som + thread_function(i); });
}
for(auto& t: vecto_Array)
{
t.join();
}
std::cout << Som << std::endl;
}
The result is always wrong. Why?
I solved the problem as follows:
void thread_function(int (*i),int (*S))
{
(*S)=(*S)+(*i);
(*i)++;
}
main()
{
std::vector<std::thread> vecto_Array;
int i=0,j=0,Som=0;
for(i=1;i<=5000;i++)
{
vecto_Array.emplace_back([&](){thread_function(&j,&Som);});
}
for(auto& t: vecto_Array)
{
t.join();
}
std::cout << Som<<std::endl;
}
But is there anyone to explain to me why it did not work when taking "i of loop" ?