admin管理员组文章数量:1794759
qt中waitForReadyRead和waitForBytesWritten函数的使用
一些见解 官方文档介绍
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()信号来实现的,如果产生这两个信号过快(就像上面的代码,死循环执行疯狂产生信号),会导致对应到槽函数的事件(信号到槽的执行是一种事件,这个事件将会到对应线程的消队列中排队等待执行)一直在消队列中疯狂阻塞,阻塞的结果就是消队列不断膨胀,从而内存不断增加,直到队列到达上限导致程序崩溃。 一定要注意超时的问题!
本文标签: 函数QTwaitForReadyReadwaitForBytesWritten
版权声明:本文标题:qt中waitForReadyRead和waitForBytesWritten函数的使用 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1686492670a73614.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论