简体   繁体   中英

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. Looking up on web I found that I can use std::this_thread::sleep_for() to achieve this (I am doing this on 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 .

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):

#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 ).
Also, it's better to seed rand using srand before calling it.

However, it may not work as expected in some environments so you may need to flush the output sequence like below:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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