QTextStream does not write until QThread :: sleep ()

It was expected that "hello again" would appear on the console 5 seconds after "hello world". But actually the console was empty for 5 seconds, after which I could see both messages. What to do to have the expected result?

#include <QThread>
#include <QTextStream>

QTextStream qout(stdout);

int main()
{
    qout << "hello world\n";
    QThread::sleep(5);
    qout << "hi again\n";
    return 0;
}

      

// The "multithreading" tag exists because I found this problem while writing a multithreaded program and that the solution can be applied to multithreaded applications.

+3


source to share


2 answers


QTextStream does not automatically clear its buffer of newline characters. The simplest solution here is to use endl, which adds a newline character and calls flush () for you:

qout << "hello world" << endl;
QThread::sleep(5);
qout << "hi again" << endl;

      

You can of course call flush () manually:



qout << "hello world\n";
qout.flush();
QThread::sleep(5);
qout << "hi again\n";
qout.flush();

      

Depending on your use case, another possibility is to rely on the QTextStream destructor calling flush ().

{
    QTextStream qout(stdout);
    qout << "hello world\n";
}
QThread::sleep(5);
{
    QTextStream qout(stdout);
    qout << "hi again\n";
}

      

+9


source


The problem is not multi-threaded. The reason is that your input is stored in buffered data that has not yet been written to stdout. To force the stream to write its data, call QTextStream :: flush () before sleep () =)



#include <QThread>
#include <QTextStream>

QTextStream qout(stdout);
int main()
{
    qout << "hello world\n";
    qout.flush();

    QThread::sleep(5);
    qout << "hi again\n";
    qout.flush();

    return 0;
}

      

+3


source







All Articles