简体   繁体   English

std::this_thread::sleep_for() 冻结程序

[英]std::this_thread::sleep_for() freezing the program

I am making a loading type function so what I wanted to do was to halt my program for a few seconds and then resume the execution inside a loop to make it look like a loading process.我正在制作一个加载类型 function 所以我想做的是暂停我的程序几秒钟,然后在循环内恢复执行,使其看起来像一个加载过程。 Looking up on web I found that I can use std::this_thread::sleep_for() to achieve this (I am doing this on linux).查找 web 我发现我可以使用std::this_thread::sleep_for()来实现这一点(我在 linux 上这样做)。 The problem I am facing is that I am unable to make it work with \r or any other way to overwrite the last outputted percentage as the program freezes as soon as I do it, however it works perfectly with \n and it's all confusing to understand why it'd work with a newline sequence but not with \r .我面临的问题是我无法使用\r或任何其他方式覆盖最后输出的百分比,因为程序一执行就冻结,但是它与\n完美配合,这一切都令人困惑了解为什么它可以使用换行符序列但不能使用\r

I am posting the sample code below, can someone tell me what am I doing wrong?我在下面发布示例代码,有人可以告诉我我做错了什么吗?

#include<iostream>
#include<chrono>
#include<thread>

int main()
{
    for (int i = 0; i<= 100; i++)
    {
        std::cout << "\r" << i;
        std::this_thread::sleep_for(std::chrono::seconds(rand()%3));
    }
    return 0;
}

I am kinda new to this topic and after some digging I found out that I am messing with the threads.我对这个话题有点陌生,经过一番挖掘后,我发现我在搞乱线程。 But still not sure why this behavior is happening.但仍然不确定为什么会发生这种行为。

This works fine on my machine (Windows 10):这在我的机器(Windows 10)上运行良好:

#include <iostream>
#include <chrono>
#include <thread>
#include <cstdlib>
#include <ctime>


int main( )
{
    std::srand( std::time( 0 ) );

    for ( std::size_t i { }; i < 100; ++i )
    {
        std::cout << '\r' << i;
        std::this_thread::sleep_for( std::chrono::seconds( std::rand( ) % 3 ) );
    }
}

I suggest that you write '\r' instead of "\r" cause here you only want to print \r character and "\r" actually prints two characters ( \r and \0 ).我建议你写'\r'而不是"\r"因为在这里你只想打印\r字符,而"\r"实际上打印两个字符( \r\0 )。
Also, it's better to seed rand using srand before calling it.此外,最好在调用之前使用srand播种rand

However, it may not work as expected in some environments so you may need to flush the output sequence like below:但是,它在某些环境中可能无法按预期工作,因此您可能需要刷新 output 序列,如下所示:

std::cout << '\r' << i << std::flush;

or like this:或像这样:

std::cout << '\r' << i;
std::cout.flush( );

These are equivalent.这些是等价的。

For more info about flush see here .有关flush的更多信息,请参见此处

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

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