睡眠和睡眠开始错误 [英] sleep and usleep start wrong

查看:142
本文介绍了睡眠和睡眠开始错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,我在主"路径中使用usleep,并在之前调用函数out.

In C++ I use usleep in my "main" path and call the function out before.

out();
usleep(4000000);

out只是在屏幕上打印一些内容.不幸的是,尽管out()功能调用在usleep命令之前,但是打印仅在4秒后才出现在屏幕上.我在用树莓做树莓.怎么不首先使用函数out();会被调用,然后usleep开始,但是反过来呢?

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?

推荐答案

在C ++中,为了减少IO的时间,我们对输出进行了缓冲.这就是说,写入屏幕/磁盘的调用并不总是写入真实设备.

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";

如果每次将"a"写入屏幕,则将花费很长时间.相反,整个缓冲区每n个字符写入一次.

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:

使用std :: flush像这样:

Use std::flush like this:

std::cout << std::flush;

Std :: endl也使用flush:

Std::endl also uses flush:

std::cout << std::endl;

这篇关于睡眠和睡眠开始错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆