C++ (Qt)#ifndef AUTOTHREADOBJ_H#define AUTOTHREADOBJ_H #include <QObject> class QWaitCondition;class QMutex; class AutoThreadObj : public QObject{ Q_OBJECT public: AutoThreadObj(QObject *parent = 0); ~AutoThreadObj(); void resume(); void stop(); public slots: void process(); private: QWaitCondition *m_condition; QMutex *m_mutex; volatile bool m_stop; signals: void finished(); };#endif // AUTOTHREADOBJ_H #include "AutoThreadObj.h" #include <QWaitCondition>#include <QMutex> #include <QDebug> AutoThreadObj::AutoThreadObj(QObject *parent) : QObject(parent) , m_condition(new QWaitCondition) , m_mutex(new QMutex) , m_stop(false){ } AutoThreadObj::~AutoThreadObj(){ } void AutoThreadObj::process(){ forever { m_mutex->lock(); m_condition->wait(m_mutex); //wait for resume if (m_stop) { m_mutex->unlock(); break; } //do something m_mutex->unlock(); } delete m_condition; delete m_mutex; emit finished();} void AutoThreadObj::resume(){ m_mutex->lock(); m_condition->wakeOne(); m_mutex->unlock();} void AutoThreadObj::stop(){ m_mutex->lock(); m_stop = true; m_condition->wakeOne(); m_mutex->unlock();}
C++ (Qt)#ifndef QTMPWND_H#define QTMPWND_H #include <QtGui/QMainWindow>#include "ui_qtmpwnd.h" class QThread;class AutoThreadObj;class QCloseEvent; class QTmpWnd : public QMainWindow{ Q_OBJECT public: QTmpWnd(QWidget *parent = 0, Qt::WFlags flags = 0); ~QTmpWnd(); private: Ui::QTmpWndClass ui; QThread *m_autoThread; AutoThreadObj *m_autoObj; protected: void closeEvent(QCloseEvent *e);}; #endif // QTMPWND_H #include "qtmpwnd.h" #include <QThread>#include <QCloseEvent>#include "autothreadobj.h" QTmpWnd::QTmpWnd(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags){ ui.setupUi(this); m_autoThread = new QThread; m_autoObj = new AutoThreadObj; m_autoObj->moveToThread(m_autoThread); connect(m_autoThread, SIGNAL(started()), m_autoObj, SLOT(process()), Qt::QueuedConnection); connect(m_autoObj, SIGNAL(finished()), m_autoThread, SLOT(quit()), Qt::QueuedConnection); m_autoThread->start();} QTmpWnd::~QTmpWnd(){ } void QTmpWnd::closeEvent(QCloseEvent *e){ if (m_autoThread->isRunning()) { m_autoObj->stop(); m_autoThread->quit(); m_autoThread->wait(); } delete m_autoObj; delete m_autoThread; e->accept();}
C++ (Qt)void AutoThreadObj::process(){ forever { m_mutex->lock(); m_condition->wait(m_mutex); //wait for resume if (m_stop) { m_mutex->unlock(); break; } //do something m_mutex->unlock(); } delete m_condition; delete m_mutex; emit finished();}