概述
一些见解
官方文档介绍
Blocks until new data is available for reading and the readyRead() signal has been emitted, or until msecs milliseconds have passed. If msecs is -1, this function will not time out.
Returns true if new data is available for reading; otherwise returns false (if the operation timed out or if an error occurred).
This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread.
If called from within a slot connected to the readyRead() signal, readyRead() will not be reemitted.
Reimplement this function to provide a blocking API for a custom device. The default implementation does nothing, and returns false.
Warning: Calling this function from the main (GUI) thread might cause your user interface to freeze.
文档没有直接说明会产生error信号:
在超时的时候会触发error(QAbstractSocket::SocketError)信号(SocketTimeoutError),一不注意可能就会产生一个bug
举例:
//尝试在waitForReadyRead()函数之前有数据过来,当执行wait函数时,会直接返回true。
//在阻塞期间来数据,会返回true。
//阻塞默认参数30000ms,超时返回false。
while (written != data.size())
{
if (mSocket->waitForBytesWritten())
{
written += mSocket->write(data.mid(written, data.size() - written));
}
}
if (port.waitForReadyRead(10))
{
port->readAll();
}
因为waitfor系列函数是通过readyRead()信号与bytesWritten()信号来实现的,如果产生这两个信号过快(就像上面的代码,死循环执行疯狂产生信号),会导致对应到槽函数的事件(信号到槽的执行是一种事件,这个事件将会到对应线程的消息队列中排队等待执行)一直在消息队列中疯狂阻塞,阻塞的结果就是消息队列不断膨胀,从而内存不断增加,直到队列到达上限导致程序崩溃。
一定要注意超时的问题!
最后
以上就是微笑糖豆为你收集整理的qt中waitForReadyRead和waitForBytesWritten函数的使用的全部内容,希望文章能够帮你解决qt中waitForReadyRead和waitForBytesWritten函数的使用所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复