简体   繁体   中英

QTextStream doesn't write before QThread::sleep()

It was expected that "hi again" appears on console 5 seconds after "hello world". But actually, the console was empty for 5 seconds and after that I could see both messages. What should I 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 is there since I found this problem during writing a multithreaded program, and that the solution may be applied to multithreaded applications.

QTextStream doesn't automatically flush its buffer on a newline character. The easiest 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;

Of course, you could 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's destructor calling flush().

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

The problem is not related to multithread. The reason is that your input is being stored in buffered data, which has not been written to stdout yet. In order to force the stream to write its data, please 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;
}

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