问题
In C++ I use usleep
in my "main" path and call the function out
before.
out();
usleep(4000000);
out
just prints something on the screen. Unfortunately the print appears on the screen only after 4 seconds, though the out()
function call is before the usleep
command. I work on a raspberry with raspbian. How can it be that not first the function out()
; is called and then usleep
starts but the other way round?
回答1:
In C++ in order to decrease the time of IO we have buffered output. What that means, is that calls that write to screen/disk do not always write to the real device.
Let's take for example this code:
for (int x = 0; x < 10000; x++)
std::cout << "a";
If "a" would be written to the screen each time, it would take a long time. Instead, the whole buffer is written every n characters.
In order to write the non full buffer to the screen you have several options:
Use std::flush like this:
std::cout << std::flush;
Std::endl also uses flush:
std::cout << std::endl;
来源:https://stackoverflow.com/questions/25932684/sleep-and-usleep-start-wrong