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
This has nothing to do with threads, whatsoever.
std::cout<<i+1<<" ";
Formatted output operations on a std::ostream are buffered. This is now sitting in cout's internal buffer, waiting for more stuff to be written, until it can all be written out in one big chunk, and/or until there's a newline.
std::cout<<"\n";
Like this. As you've discovered by yourself.
Without a newline you need to explicitly flush it yourself:
std::cout<<i+1<<" "<<std::flush;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With