C++ sleep_for method is not working as expected. I'm trying to write a program that prints from 1 to 10 but with some time gap between each print.
1 (after 1 sec) 2 (after 1 sec) 3 . . . and so on.
the code is:
#include <iostream>
#include <thread>
#include <chrono>
void produce()
{
for(int i=0;i<10;i++)
{
std::cout<<i+1<<" ";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout<<"\n";
}
int main()
{
std::cout<<"Starting the thread\n";
std::thread thread1(produce);
thread1.join();
std::cout<<"Thread finished execution\n";
return 0;
}
The output of the above program is:
wait for 10 seconds....then immediately print from 1 to 10. ( why is this happening ? )
If I change the produce method to:
void produce()
{
for(int i=0;i<10;i++)
{
std::cout<<i+1<<" ";
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout<<"\n";
}
}
Then, I'm getting the expected result ( all I did for put the cout inside the loop and it makes the program wait for a second before printing the next number.
Is there something that I don't understand about c++ threads or this is an actual issue ? Thanks in advance