GMa*_*han 4 c++ qt multithreading
我正在尝试为 Scanner 类创建一个线程,该类处理此特定类的所有事件,从而释放 GUI 线程。我的 GUI 上有一个退出按钮,它只是调用 qApp->quit() 来退出应用程序,但我不确定如何处理我的 Scanner 类中的线程。退出应用程序时,我在调试日志中看到以下错误。
QThread::wait: Thread tried to wait on itself
QThread::wait: Thread tried to wait on itself
QThread: Destroyed while thread is still running
Run Code Online (Sandbox Code Playgroud)
在 Scanner.cpp 中(省略其他功能)
Scanner::Scanner() :
{
this->moveToThread(&m_thread);
connect(&m_thread, &QThread::finished, this, &QObject::deleteLater);
connect(this, SIGNAL(StartEnroll()), this, SLOT(StartEnrollment()));
m_thread.start();
}
Scanner::~Scanner()
{
m_thread.quit(); // Not sure if this is the correct
m_thread.wait();
}
Run Code Online (Sandbox Code Playgroud)
在主Window.cpp中(省略其他功能)
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->ExitButton, SIGNAL(released()), this, SLOT(Quit()));
connect(&m_scanner, SIGNAL(FinishedEnroll(bool)), this, SLOT(EnrollDone(bool)));
}
void MainWindow::Quit()
{
close();
qApp->quit();
}
Run Code Online (Sandbox Code Playgroud)
在多线程应用程序中如何安全退出应用程序的任何指示。
您需要让Scanner全班知道应用程序正在退出。
将以下行添加到的构造函数 MainWindow
connect(qApp, SIGNAL(aboutToQuit()), &m_scanner, SLOT(deleteLater()));
Run Code Online (Sandbox Code Playgroud)
更新:
connect(&m_thread, &QThread::finished, this, &QObject::deleteLater);
Run Code Online (Sandbox Code Playgroud)
不应该在的构造函数中 Scanner
和
m_thread.quit();
m_thread.wait();
Run Code Online (Sandbox Code Playgroud)
不应该在析构函数中 Scanner
事实上,m_thread不应该Scanner以任何方式参与其中。本QThread类并不代表一个线程,它是一个线程管理器,应拥有并从那里创建它的线程控制。
在 Qt 中有许多使用线程的方法,许多没有很好地记录。如果您想使用
workerObject->moveToThread(&thread);
thread.start();
Run Code Online (Sandbox Code Playgroud)
使用线程的方式,那么m_thread应该是MainWindow类的成员,并且这些函数调用应该在它的构造函数中进行。