简体   繁体   English

QTextStream在QThread :: sleep()之前不写

[英]QTextStream doesn't write before QThread::sleep()

It was expected that "hi again" appears on console 5 seconds after "hello world". 预计在“hello world”之后5秒,“hi hi”会出现在控制台上。 But actually, the console was empty for 5 seconds and after that I could see both messages. 但实际上,控制台是空的5秒钟,然后我可以看到这两个消息。 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. QTextStream不会自动刷新换行符上的缓冲区。 The easiest solution here is to use endl, which adds a newline character and calls flush() for you: 这里最简单的解决方案是使用endl,它会添加换行符并为您调用flush():

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

Of course, you could call flush() manually: 当然,您可以手动调用flush():

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的析构函数调用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. 原因是您的输入存储在缓冲数据中,尚未写入stdout。 In order to force the stream to write its data, please call QTextStream::flush() before sleep() =) 为了强制流写入数据,请在sleep()=之前调用QTextStream :: flush()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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