sleep and usleep start wrong

戏子无情 提交于 2019-12-26 09:16:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!