[Qt-interest] Deleting a QThread with event loop.

Piotr Qzieblo qtpiotrek at gmail.com
Wed Mar 18 12:56:37 CET 2009


Hi,

I am wondering what is the most Qtish way of deleting a thread with event loop.

I have a class ActiveObject that extends QThread, which has its own event loop:

class ActiveObject: public QThread
{

Q_OBJECT

public:
    ActiveObject();
    virtual ~ActiveObject();

    // ... my stuff (could be for example a class that read and write
to a socket using signal and slots mechanism)

protected:
    virtual void run();


signals:
    void stopSig();
    // ...

protected slots:
    virtual void stopSlot();

// ...
};

}

ActiveObject::ActiveObject()
{
	moveToThread(this);
	connect(this, SIGNAL(stopSig()), this, SLOT(quit()), Qt::QueuedConnection);
}

ActiveObject::~ActiveObject()
{
	emit stopSig();
	wait();
}

void ActiveObject::run()
{
	exec();
}

void ActiveObject::stopSlot()
{
	QCoreApplication::processEvents();
	exit();
}

The thread would be created and destroyed from the main thread:

int main()
{
        QCoreApplication app;
	ActiveObject a;
	a.start();
	app.exec();
	// someone has broken the main event loop
	// now the destructors are called
}

Is that OK?

BTW, I find there's a lack of info/tutorials about non-gui
multi-threaded development. For example, I have passed a lot of time
trying to find out where to put the moveToThread() calls. This could
be easily explained by a simple tutorial...

Also, why do I have to use QCoreApplication::processEvents() before
exit even if I am sure that there will be no more queued signals
emitted after emitting stopSig signal? I didn't investigate QT library
source but it seems that two signals emitted in different threads (in
queued connection mode) are not guaranteed to be queued in the order
they were emitted. Am I right?

Thanks,
Piotrek




More information about the Qt-interest-old mailing list