多线程Qt应用程序在退出时不会停止



我正在编写一个简单的Qt程序来捕获来自相机的视频源(使用OpenCV)。我正在使用一个循环、捕获图像并将其馈送到MainWindow对象的QThread对象。这正在正常工作。

问题是,当我关闭时,应用程序(即按"X")相机捕获线程停止并且 gui 消失。但是该程序仍在后台运行。我还在应用程序输出中收到一条警告,说:

QThread:在线程仍在运行时销毁。

退出应用程序时如何完全停止应用程序?

主.cpp

#include <QApplication>
#include "application.h"
using namespace cv;
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Application app;
    app.init();
    return a.exec();
}

应用程序.h

#include "mainwindow.h"
#include "camerathread.h"
#include "mathandler.h"
#include "tools.h"
#include "opencv2/core/core.hpp"
#ifndef APPLICATION
#define APPLICATION
class Application : public MatHandler{
    MainWindow w;
    CameraThread ct;
public:
    Application() {
        w.setFixedSize(800,600);
    }
    void init() {
        ct.setMatHandler(this);
        ct.start();
        w.show();
    }
    void handleMat(cv::Mat mat) {
        QImage qImage = toQImage(mat);
        w.setImage(qImage);
    }
};
#endif // APPLICATION

相机线程

#include <QThread>
#include "mathandler.h"
#include "opencv2/highgui/highgui.hpp"
#ifndef CAMERATHREAD
#define CAMERATHREAD
class CameraThread : public QThread {
    MatHandler *matHandler;
public:
    ~CameraThread() {
    }
    void setMatHandler(MatHandler *h) {
        matHandler = h;
    }
private: void run() {
        cv::VideoCapture vc(0);
        if (vc.isOpened()) {
            for(;;) {
                cv::Mat img;
                vc >> img;
                matHandler->handleMat(img);
            }
        }
    }
};
#endif // CAMERATHREAD

该程序包含的代码比这更多,但我只包含我认为与问题相关的代码。如有必要,我会发布其余的。

你的代码有一些主要问题。首先,在你的运行函数中,无休止的for循环将导致你的线程永远不会停止,除非你自己管理线程终止,比如:

while(!finishThread)
{
   cv::Mat img;
   vc >> img;
   matHandler->handleMat(img);
}

应将finishThread设置为true应用程序何时关闭。只需提供一个插槽,您可以在其中设置finishThread的值。当您要终止线程时,发出一个信号,该信号连接到该插槽,具有true值。之后等待线程正确完成几秒钟,如果未完成,则强制它终止:

emit setThreadFinished(true); //Tell the thread to finish
if(!ct->wait(3000)) //Wait until it actually has terminated (max. 3 sec)
{
    ct->terminate(); //Thread didn't exit in time, probably deadlocked, terminate it!
    ct->wait(); //We have to wait again here!
}

此外,您不应直接从其他线程调用handleMat函数。它可能会导致应用程序崩溃或导致未定义的行为。为此,请使用信号/插槽机制。将来自线程的信号连接到该槽,并在每次要调用它时沿参数发出信号。

另一点是,您最好从QObject派生类并使用moveToThread。您可以在类的构造函数中执行此操作:

th = new QThread();
this->setParent(0);
this->moveToThread(th);
QObject::connect(th,SIGNAL(started()),this,SLOT(OnStarted()));
QObject::connect(th,SIGNAL(finished()),this,SLOT(OnFinished()));
th->start();

初始化和终止任务应分别在OnStarted()OnFinished()槽中完成。您可以使用一个工作器函数来运行重复操作。

同样在Application类的析构函数中,以某种方式退出线程,如所述。

最新更新