繁体   English   中英

试图了解刷新缓冲区问题的影响

[英]trying to understand the effect of flushing a buffer problem

我是 C++ 的完整初学者,所以如果我的问题听起来很愚蠢或其他什么,我深表歉意。

我一直在阅读一本关于 stream 缓冲区的简单介绍的书,在某些情况下刷新缓冲区很重要,因此为了了解效果,我运行了以下代码:

代码1:

#include <iostream>
#include <thread>
#include <chrono>   
using namespace std;
      
int main()
{
  for (int i = 1; i <= 5; ++i)
  {
      cout << i << " ";
      this_thread::sleep_for(chrono::seconds(1));
  }
  cout << endl;
  return 0;
}

代码2:

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;

int main()
{
   for (int i = 1; i <= 5; ++i)
   {
      cout << i << " " << flush;
      this_thread::sleep_for(chrono::seconds(1));
   }
   return 0;
}

两个代码都给出相同的 output,完全没有区别,它们打印 1 sleep for 1 second then 2, sleep for another second,依此类推。

我尝试在 DevC++ 和 CodeBlocks 中运行代码,结果相同。

书上说code1的结果——>“程序等待5秒,一次打印所有数字”,code2的结果——>“程序打印数字等待1秒,打印第二个数字和很快”。

我真的不明白出了什么问题。

这是一个带有和不带有异常的刷新的示例(它应该在最后一行被刷新之前终止程序):

#include <iostream>
int main() {
    std::cout << "test with flush" << std::flush;
    std::cout << "test without flush";
    throw;
}

当编译并在godbolt中运行时,我看到:

Program returned: 139
terminate called without an active exception
test with flush

但没有提到“没有刷新的测试”,因为程序在它可以自动刷新之前就结束了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM