有和没有换行字符的睡眠行为

Behavior of sleep with and without new line character

本文关键字:字符 换行      更新时间:2023-10-16

考虑下面的代码,其中有两个测试区域

在第一次测试中(测试1::不加新线),程序按规定休眠10秒(5*2)。但是所有的5 *都是only after the 10 seconds finished.

在第二次测试中(测试2::带新线),程序休眠10秒(5*2)。但是# s是在每两秒钟睡眠后打印的。

这背后的逻辑是什么?

Compiler:g++
platform:UNIX

,

我研究睡眠是不是标准库的一部分?我们需要使用pthread.h

如果不包含pthread.h

 #include<iostream>
 int main()
 {
    using namespace std;
 // Test 1 :: without new line
 for(int i=0;i<5;i++)
 {
    sleep(2);
    cout<<"*";
 }
 cout<<"n";
 // Test 2 :: with new line
 for(int i=0;i<5;i++)
 {
    sleep(2);
    cout<<"#n";
 }
    return 0;
 }

当连接到终端时,std::cout是行缓冲的。您需要一个显式的cout << flush;来使每个*单独出现。

关于您的第一个问题,cout不会立即冲洗。它执行的时间取决于许多因素,但在这种情况下,它似乎只在看到换行符时才刷新。如果要强制刷新,可以使用

cout << flush;
// or
cout.flush();

关于pthreads:很可能你的编译器在默认情况下只包含了所需的头文件