0

Below is some simple code; please note that there is a printf statement before there is a call to waitFor(). Why does the program halt for three seconds and then print the message?

int main(int argc, char* argv)
{
    producer();

    return 0;
}

void waitFor(unsigned int secs) {
    unsigned int retTime = time(0) + secs;   // Get finishing time.
    while (time(0) < retTime);               // Loop until it arrives.
}

static void *producer()
{
    int s = 3;
    printf("Busy for %d seconds", s);
    waitFor(s);
    return NULL;
}
8protons
  • 3,591
  • 5
  • 32
  • 67

2 Answers2

1

It's likely because you're not letting the output flush before you spin-wait the CPU.

Your waitFor routine isn't really the right way to do it. Take a look at using sleep().

On my mac, if I add a newline to the message, it outputs immediately without needing to flush.

    printf("Busy for %d seconds\n", s);
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Jim B.
  • 4,512
  • 3
  • 25
  • 53
  • Thanks, Jim. I had used the `waitFor` routine because of this answer http://stackoverflow.com/questions/3930363/implement-time-delay-in-c/3930477#3930477 – 8protons Nov 21 '16 at 03:07
  • 1
    Jim Baldwin, are there C systems which flush in sleep() calls? AFAIK, at least libc/gcc and MSVC only flush on full buffer or explicit call. For them, either busy loop or sleep() will have no effect. – theamk Nov 21 '16 at 03:10
  • Weird. It's better to yield the CPU (and let other threads run) while you're waiting, which is what sleep does. This waitFor() is hammering on the time() call which is going to tie up resources. FYI: https://linux.die.net/man/3/sleep – Jim B. Nov 21 '16 at 03:11
  • @JimBaldwin I implemented `sleep(s)` after including ``. I got the same result where printing happens after sleeping :/ – 8protons Nov 21 '16 at 03:11
  • 2
    Yes, the root problem is that the output is not flushed. The method of sleeping is a separate issue, and maybe just making it worse. – Jim B. Nov 21 '16 at 03:13
  • @JimBaldwin Found the solution. Needed to print the buffer, derp. This is what happens when a novice takes a year hiatus from `C` lol. Thanks Jim and @theamk – 8protons Nov 21 '16 at 03:13
  • Actually, if you just add \n to your printf it flushes before the spinwait. – Jim B. Nov 21 '16 at 03:17
1

How are you running this program? Sometimes the output of printf() is buffered, and only appears when you print a lot of data or when the program exits. Two easy ways to fix it are:

  • use stderr: printf( -> fprintf(stderr,
  • flush after use: call fflush(stdout) after printf
theamk
  • 1,420
  • 7
  • 14