简体   繁体   中英

Thread sleep does not continue execution after timeout

Why does thread block?

Hello i am trying to pause a thread for a given number of seconds.I am running the program from the command line. The program enters the "sleep" but does not print anything , until i press CTRL+C at which point it prints everything it had to print in bulk.Why does it work in the background ?Why does it not print to the console after each sleep_for ?

main.cpp

#include<iostream>

#include<chrono>

#include<thread>

#include<string>

#include <unistd.h>

int main(int argc,char *argv[])
{

    std::cout<<"Started daemon..."<<std::endl;

    std::string hostString(argv[1]);
    std::cout<<"HostName:"<<hostString<<std::endl;
        std::cout<<"Port:"<<atoi(argv[2]);
    int i=0;

    while(true){
        std::cout<<"Iterations:"<<i;
        std::this_thread::sleep_for (std::chrono::seconds(1));
    if(i++>10000) i=0;

    }

    return 0; 

}

Many output operations are buffered. That is they will wait to actually write to the string until they fill up the buffer. This means that there can be a delay between when you tell it o print and when it actually does.

To fix this you can use the flush stream manipulator to force the contents to be written. That would make your code look like

while(true){
    std::cout<<"Iterations:"<<i << std::flush;
    std::this_thread::sleep_for (std::chrono::seconds(1));
    if(i++>10000) i=0;
}

If your stream is line buffered then you could also just print a newline like

while(true){
    std::cout<<"Iterations:"<<i << "\n";
    std::this_thread::sleep_for (std::chrono::seconds(1));
    if(i++>10000) i=0;
}

Output to std::cout is, generally speaking, line buffered meaning nothing will appear at the console until either a newline is written or the buffered data reaches a certain size. Try...

std::cout << "Iterations: "<< i << "\n";

Or, force a flush with...

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

std::cout is a buffered stream. That means whatever you write to that stream first goes into an internal buffer. That buffer is only emptied out ("flushed") when the runtime/system decides to do so. This is done mainly for performance reasons. It allows the runtime/system to not do tons of tiny I/O operations all the time, which would incur quite some overhead, but wait until enough output has accumulated so that expensive I/O can be done in larger batches.

You can call the flush() method to explicitly force the stream to be flushed or "output" std::flush to the stream:

std::cout << "bla" << std::flush

If you want to flush after each line, use std::endl , which outputs a newline character and also flushes.

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