C ++线程睡眠不一致 [英] C++ thread sleeping inconsistency

查看:93
本文介绍了C ++线程睡眠不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿那里的家伙。



我用c ++获得了极好的奇怪问题...希望有人能帮我理解根本原因......

代码:

 for(int i = 0; i< 10; i ++){
std :: cout<< i<< ;
std :: this_thread :: sleep_for(std :: chrono :: milliseconds(1000));
}





现在 - 问题是如果我在Windows中运行 - 输出正如预期的那样 - 每秒都会将一个数字打印到控制台中。并且 - 在ubuntu机器上尝试这个时它什么也没显示,10秒后立即打印所有数字。



任何想法为什么它不会像Windows一样每秒打印输出?



我尝试了什么:



试过建造并运行这个在CodeLite中有和没有集成终端。尝试使用简单的终端手动编译和运行(尝试过c ++ 11和c ++ 14)。

解决方案

尝试将一个std :: flush添加到cout行。

 std :: cout<< i<< <<的std ::冲洗; 


Hey there guys.

Superb weird issue I got with c++... hope anyone can help me out understanding root cause...
The code:

for(int i = 0; i < 10; i++) {
    std::cout << i << " ";
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}



Now - the thing is that if I run this in windows - the output comes as expected - every second a number is printed into console. And - when trying this on ubuntu machine it shows nothing and after 10 seconds prints all numbers instantly.

Any idea why it does not print the output every second as in windows?

What I have tried:

Tried building and running this in CodeLite with and without integrated terminal. Tried compiling and running using simple terminal manually (tried c++11 and c++14).

解决方案

Try adding a std::flush to the cout line.

std::cout << i << " " << std::flush;


这篇关于C ++线程睡眠不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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