typedef void(QObject::*threadFunction)();class K_ThreadManager : private QObject, public QThread{ Q_OBJECTprotected:public: K_ThreadManager(QObject *parent, const char *name = 0); ~K_ThreadManager(); void initApplyFunction(threadFunction func); void apply();protected: void customEvent(QCustomEvent *e); void run();private: threadFunction applyFunction;signals: void closeManagerThread(K_ThreadManager*);};#endif
#include "k_threadmanager.h"#include "qapplication.h"K_ThreadManager::K_ThreadManager(QObject *parent, const char *name) : QObject(NULL, name), QThread(){ connect(this, SIGNAL(closeManagerThread(K_ThreadManager*)), parent, SLOT(slotOnEndingThread(K_ThreadManager*))); applyFunction = NULL;}K_ThreadManager::~K_ThreadManager(){}void K_ThreadManager::customEvent( QCustomEvent * e ){ switch (e->type()) { case THREAD_MANAGER_FINISHED: applyFunction = NULL; emit closeManagerThread(this); break; default: break; }}void K_ThreadManager::run(){ if (applyFunction != NULL) (this->*(applyFunction))(); QCustomEvent* event = new QCustomEvent(THREAD_MANAGER_FINISHED); event->setData(this); postEvent(this, event);}void K_ThreadManager::initApplyFunction(threadFunction func){ applyFunction = func;}void K_ThreadManager::apply(){ start();}
void AnyData::slotBuildModel(){ K_ThreadManager* thread = new K_ThreadManager(this,"build"); thread->initApplyFunction((threadFunction)(&AnyData::startBuild)); thread->apply();}void AnyData::startBuild(){ выполняются долгие нудные операции, но точно без lock и wait ...}void AnyData::slotOnEndingThread(K_ThreadManager*){ //выполняем то, что были должны после startBuild}
C++ (Qt)void K_ThreadManager::run(){ AnyData data; data.startBuild(); QCustomEvent* event = new QCustomEvent(THREAD_MANAGER_FINISHED); event->setData(this); postEvent(this, event);}
C++ (Qt)void AnyData::startBuild() { bool res = m_mutex.tryLock(); if (!res) return; //do_something m_mutex.unlock();}