[英]Buffer Overrun using Qt Threads and Signals
我必須將項目從QT5降級到QT4,並在這樣做時遇到奇怪的緩沖區溢出錯誤。 這是我的代碼:
我像這樣創建一個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();
在我的線程中,我有以下代碼:
try {
while(condition) {
...something
}
} catch(Exception e) {
emit errorMsg("Error");
}
emit finished();
我主線程中的插槽看起來像這樣:
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);
}
所有這些在QT5中都運行良好。 錯誤消息框顯示正確,並且線程被破壞。 但是在QT4(4.8.1)中,當發生錯誤並發出errorMsg()時,我得到了緩沖區溢出錯誤。 如果我不發出errorMsg(“ Error”)並僅通過調用finish()銷毀線程,則不會發生緩沖區溢出。 對這里出什么問題有任何想法嗎?
更新:如果我不訪問threadErrorMsgit中的QString起作用。 像這樣:
void MainWindow::threadErrorMsg(QString message) {
QMessageBox::critical(this, "Error", "Error", QMessageBox::Ok);
}
我究竟做錯了什么?
void MainWindow::threadFinished() {
reader = NULL;
delete thread;
thread = NULL;
}
不建議直接在插槽中刪除線程。 您應該使用deleteLater函數。
thread->deleteLater();
但是,您已經設置了要在連接中刪除的線程
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
因此,您現在嘗試將其刪除兩次!
至於緩沖區溢出,我懷疑在錯誤發生之前某些東西已經損壞了內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.