1

I am trying to do a very simply thing (yet spent hours without a result): Print one line, sleep a little, print a second line. I expect the below code to do that, however, it first sleeps then prints both lines simultaneously! Can anyone see what I'm missing here?

This is the entire code:

#include<thread>
#include<chrono>

int main() {
    printf("%s","Wait.\n");
    std::this_thread::sleep_for(std::chrono::seconds(3));
    printf("%s","Thank you for waiting.");
}

Computer info: Mac 10.14.16, Editor: CLion

iamvegan
  • 482
  • 4
  • 15
  • 1
    try `fflush(stdout);` although `'\n'` in the first printf should have flushed – bolov Jun 24 '20 at 17:35
  • Worked on my machine. With or without a `fflush`. But I had to add code. Maybe the bug isn't in the code provided? A [mcve] could be helpful. The compile line used would be helpful too, which will show *how* it was compiled and linked. – Eljay Jun 24 '20 at 17:39
  • @bolov this is only true if the device is determined to be interactive – WrathOfTux Jun 24 '20 at 17:41
  • @Eljay @WrathOfTux `fflush` worked in my case. It looks like it depends on the compiler or machine. For instance in Leetcode's editor it _doesn't work_ with or without `fflush`. On this [editor](https://onlinegdb.com/ryPcmzWRL) it _works_ with or without `fflush`. – iamvegan Jun 24 '20 at 17:56
  • @Eljay it was almost the entire code, updated my question anyway. – iamvegan Jun 24 '20 at 18:00

1 Answers1

3

printf doesnt necessarily flush the buffer, which is why you dont see it until the thread resumes from sleep (it does this because it notices the thread is inactive). To force a flush add fflush(stdout); before the call to thread sleep.

WrathOfTux
  • 135
  • 1
  • 6