[英]Buffer Overrun using Qt Threads and Signals
I have to downgrade a project from QT5 to QT4 and get a weird buffer overrun error when doing so. 我必须将项目从QT5降级到QT4,并在这样做时遇到奇怪的缓冲区溢出错误。 Here's my code:
这是我的代码:
I create a QThread like so: 我像这样创建一个QThread:
thread = new QThread;
reader = new Reader();
reader->setParams(samplingRate);
reader->moveToThread(thread);
connect(thread, SIGNAL(started()), reader, SLOT(read()));
connect(reader, SIGNAL(finished()), thread, SLOT(quit()));
connect(thread, SIGNAL(finished()), this, SLOT(threadFinished()));
connect(reader, SIGNAL(finished()), reader, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
connect(reader, SIGNAL(errorMsg(QString)), this, SLOT(threadErrorMsg(QString)));
thread->start();
In my thread I have the following code: 在我的线程中,我有以下代码:
try {
while(condition) {
...something
}
} catch(Exception e) {
emit errorMsg("Error");
}
emit finished();
And the Slots in my main thread look like this: 我主线程中的插槽看起来像这样:
void MainWindow::threadFinished() {
reader = NULL;
delete thread;
thread = NULL;
}
void MainWindow::threadErrorMsg(QString message) {
QMessageBox::critical(this, "Error", ("Error: " + message).toStdString().c_str(), QMessageBox::Ok);
}
All of this worked well in QT5. 所有这些在QT5中都运行良好。 The error message box was displayed correctly and the thread was destroyed.
错误消息框显示正确,并且线程被破坏。 In QT4 (4.8.1) however I get a buffer overrun error when an error occurs and errorMsg() is emitted.
但是在QT4(4.8.1)中,当发生错误并发出errorMsg()时,我得到了缓冲区溢出错误。 The buffer overrun does not occur if I don't emit the errorMsg("Error") and destroy the thread only by calling finished().
如果我不发出errorMsg(“ Error”)并仅通过调用finish()销毁线程,则不会发生缓冲区溢出。 Any ideas on what's wrong here?
对这里出什么问题有任何想法吗?
Update: If i don't access the QString in threadErrorMsgit does work. 更新:如果我不访问threadErrorMsgit中的QString起作用。 Like so:
像这样:
void MainWindow::threadErrorMsg(QString message) {
QMessageBox::critical(this, "Error", "Error", QMessageBox::Ok);
}
What am I doing wrong? 我究竟做错了什么?
void MainWindow::threadFinished() {
reader = NULL;
delete thread;
thread = NULL;
}
Deleting the thread directly in the slot is not advised. 不建议直接在插槽中删除线程。 You should use the deleteLater function.
您应该使用deleteLater函数。
thread->deleteLater();
However, you've already setup the thread to be deleted in the connection 但是,您已经设置了要在连接中删除的线程
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
So you're now trying to delete it twice! 因此,您现在尝试将其删除两次!
As for the buffer-overrun, I suspect something has corrupted memory before the error has occurred. 至于缓冲区溢出,我怀疑在错误发生之前某些东西已经损坏了内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.