I have a code that does something similar to the following repeatedly over a loop:
$ cat test.c
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
char arr[6] = {'h','e','l','l','o','!'};
for(int x=0; x<6 ; x++){
printf("%c",arr[x]);
usleep(1000000);
printf("%c",arr[x]);
usleep(1000000);
}
printf("\n");
return 0;
}
I see that printf()
executes one after the other WITHOUT any delay (due to usleep
), and then the program sleeps for the total usleep
time at the end before the next iteration. Seems like all the usleep()
calls happen together in the end.
I tried -O0
flag in gcc, because I suspected its the effect of compiler optimization. But I guess -O0
flag does not disable whatever optimization category this case falls under (if my guess is correct about the compiler being the reason for this behavior).
I am trying to understand the reason for this behavior and how to achieve the desired behavior from my program.
Note: I know it might be possible to replace usleep()
with some compute-heavy function call that take an equivalent amount of time, but that is not the solution I am looking for.