user3810155
user3810155

Reputation:

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.

Upvotes: 3

Views: 235

Answers (2)

MrEricSir
MrEricSir

Reputation: 8242

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";
}

Upvotes: 8

David Chik
David Chik

Reputation: 53

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;
}

Upvotes: 2

Related Questions