简体   繁体   English

c ++,sleep和循环

[英]c++, sleep, and loops

Ok, this is just out of curiousity, but why does the sleep function NOT work in a loop, or how can I Get it to work in a loop? 好吧,这只是出于好奇,但为什么睡眠功能不能在循环中工作,或者我怎样才能让它在循环中工作?

for(int i = 0; i < 5; i++) { 
     cout << i << endl; 
     sleep(2); 
} 

cout is buffered, meaning its contents aren't always written to the console right away. cout是缓冲的,这意味着它的内容并不总是立即写入控制台。 Try adding cout.flush() right before sleep(2); 尝试在sleep(2);前添加cout.flush() sleep(2);

If that isn't working for you you could try this code: 如果这不适合您,您可以尝试以下代码:

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

...

for(int i = 0; i < 5; i++) { 
     cout << i << endl; 
     Sleep(2000); 
} 

Dave has already given you the answer, so I won't touch on that. 戴夫已经给你答案,所以我不会谈到这个。 However, if its purely for debugging or prototype code, you could also pipe the output to std::cout's sibling, std::cerr, which is unbuffered to begin with. 但是,如果它纯粹用于调试或原型代码,您也可以将输出传递给std :: cout的兄弟,std :: cerr,它是无缓冲的。 This means you do not need to call flush explicitly and you do not need to add an endl to your output. 这意味着您不需要显式调用flush,也不需要在输出中添加endl。

In my humble opinion, this program should work correctly. 以我的拙见,这个程序应该正常工作。 Maybe your std::cout is redirected somewhere else? 也许你的std :: cout被重定向到其他地方? You don't call the correct sleep() function (but no header provided)? 你没有调用正确的sleep()函数(但没有提供头文件)? Or other problem? 还是其他问题? But it should work. 但它应该工作。

Have you tried unrolling the loop to see if that behaves the same way? 您是否尝试展开循环以查看其行为是否相同?

cout << 1 << endl;
sleep(2);
cout << 2 << endl;
sleep(2);
// Etc.

Assuming that behaves the same way, even though std::endl is supposed to flush the buffer, it really does look like dave.kilian has the right idea that cout isn't getting flushed until the program (presumably) terminates. 假设行为方式相同,即使std :: endl应该刷新缓冲区,它确实看起来像dave.kilian有正确的想法,cout没有被刷新,直到程序(可能)终止。

In that case, try doing the std::flush and see if that helps - it's possible you have a bug (missed feature?) in your standard library. 在这种情况下,尝试执行std :: flush并查看是否有帮助 - 您的标准库中可能存在错误(错过功能?)。

Another thing to try is to redirect the output to a file while watching it with tail -f in another window. 另一件事是将输出重定向到文件,同时在另一个窗口中使用tail -f观察它。 See if the same delay occurs when redirected. 查看重定向时是否发生相同的延迟。

Finally try playing with the compiler's optimization level and see if that changes the results. 最后尝试使用编译器的优化级别,看看是否会改变结果。

尝试Sleep()而不是sleep()

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

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