firemail
标题: 基于Qt的线程安全退出 [打印本页]
作者: Qter 时间: 2020-12-3 17:49
标题: 基于Qt的线程安全退出
https://blog.csdn.net/z1houcheng12/article/details/80595166
首先,QThread的用法有两种:
(1)继承自QThread类:
- #ifndef CHILDTHREADA_H
- #define CHILDTHREADA_H
- #include <QThread>
- #include <QMutex>
- class ChildThreadA : public QThread
- {
- Q_OBJECT
- public:
- explicit ChildThreadA(QWidget *parent = 0);
- ~ChildThreadA();
- void exitThread();
- protected:
- void run();
- private:
- bool m_isExist;//控制线程退出
- QMutex m_mutex;
- };
- #endif // CHILDTHREADA_H
- #include "ChildThreadA.h"
- ChildThreadA::ChildThreadA(QWidget *parent) :
- QThread(parent),
- m_isExist(false)
- {
- }
- ChildThreadA::~ChildThreadA()
- {
- delete ui;
- }
- void ChildThreadA::exitThread()
- {
- m_mutex.lock();
- m_isExist = true;
- m_mutex.unlock();
- }
- void ChildThreadA::run()
- {
- while (1)
- {
- m_mutex.lock();
- if(m_isExist)
- {
- break;
- }
- m_mutex.unlock();
- //do something
- }
- m_mutex.unlock();
- }
复制代码 在自定义的线程类中通过使用m_isExist变量控制线程的退出。在外部调用退出线程时应该这样:
- childThread->exitThread();
- if (childThread->wait())
- {
- //m_capPicThread->terminate();
- }
复制代码
首先调用退出线程接口,重置标识符的值;程序会阻塞再wait()处直到while循环退出,关于terminate()这行代码要不要都可以,因为可以执行到此,whllie循环肯定已经退出。
(2)自定义QObject类型,moveToThread():
#ifndef MYOBJECT_H#define MYOBJECT_H#include <QObject>class MyObject : public QObject{ Q_OBJECTpublic: explicit MyObject(QObject *parent = 0);signals:public slots:};#endif // MYOBJECT_H#include "MyObject.h"MyObject::MyObject(QObject *parent) : QObject(parent){ }MyObject *object = new MyObject;
QThread *thread = new QThread;
object->moveToThread(thread);
这种做法在线程退出时,因为子线程的运行是在槽函数中进行的,所以首先应该断开槽函数的连接
disconnect();然后使用
thread ->quit();
thread ->wait();使线程正常退出。
欢迎光临 firemail (http://firemail.wang:8088/) |
Powered by Discuz! X3 |