为什么输出缓冲区仍然立即刷新而不是等待10秒才显示

问题描述 投票:0回答:1

根据

cout
对象的使用,内容会先存储到输出缓冲区中,直到触发条件发生或程序结束。

然后刷新输出缓冲区。

最后终端显示内容。

但它立即显示。

#include <iostream>
#include <windows.h>

int main() {
    std::cout << "Hello, World!";
    Sleep(10000);
    return 0;
}

如何在输出流上体现

cout
方法的缓冲效果?
还是跟操作系统有关?

c++ buffer std
1个回答
0
投票

一般情况下,std::cout 默认情况下是不缓冲的:只要sync_with_stdio 处于活动状态,写入 std::cout 缓冲区的每个字节都会立即推送到 stdout 缓冲区。

stdout 在 POSIX 中默认是行缓冲的,因此如果您在 Linux 上使用 gcc 运行上述程序(使用 C++ sleep 而不是 Windows Sleep),直到暂停后您才会观察到输出。

基于“睡眠(5000);”然而,这是使用Windows。在那里,C I/O 流不会被缓冲。您可以通过替换 std::cout << "test"; with printf("test");. The output still appears immediately.

来观察到这一点

如果您在标准输出上启用缓冲,您仍然可以使 Windows 延迟输出:

#include <iostream>
#include <cstdio>
#include <windows.h>

int main()
{
    char buf[BUFSIZ];
    std::setbuf(stdout, buf);
    std::cout << "test";
    // std::fflush(stdout); // <- uncomment to see the text before the pause
    Sleep(5000);
    std::fflush(stdout);
    std::setbuf(stdout, NULL); // don't let the stream outlive the buffer
}

该演示不会让您观察 std::flush 的效果,因为 flash 只将 cout 的缓冲区(默认情况下甚至没有)移动到 stdout 的缓冲区中,输出位于其中,直到使用 std::fflush 刷新或隐含的手段。

要观察 std::flush,请给 std::cout 自己的缓冲区并将其与 C I/O 流断开:

#include <iostream>
#include <windows.h>

int main()
{
    char buf[BUFSIZ];
    std::ios::sync_with_stdio(false);
    std::cout.rdbuf()->pubsetbuf(buf, sizeof buf);
    std::cout << "test";
    //std::cout << std::flush; // <- uncomment to obseve the output before the pause
    Sleep(5000);
    std::cout << std::flush;
    std::cout.rdbuf()->pubsetbuf(nullptr, 0); // don't let the stream outlive the buffer
}
© www.soinside.com 2019 - 2024. All rights reserved.