PDA

View Full Version : Worker thread



doggrant
30th October 2009, 11:48
Hi,

I've got a 3rd party blocking library that i'm trying to implement into my QT GUI application. Using a QThread, signals and slots, but i'm struggling to work out the best way to do things.

The library contains a number of different API calls which I will want to call at various points, and then return the reult to the main GUI thread.

So far I've created a class as follows



class LibraryManagerThread: public QThread
{
Q_OBJECT
public:
LibraryManagerThread();
~LibraryManagerThread();

protected:
void run();

signals:
void done(); // Signal back to main GUI thread when work is done.

private slots:
/* place slots for each blocking api call here */
};


In the class code I have the following :-



LibraryManagerThread::LibraryManagerThread()
{
// We have to do this to make sure our thread has the
// correct affinity.
moveToThread(this);

start();
}

void LibraryManagerThread::run()
{
// This starts the event loop.
exec();
}


So the event loop will process any events I pass to it. So what i'm thinking is to signal from the main event loop to this thread, and then signal back to the main event loop once the work has been done.

However, i'm wondering how best to make this code portable, because using my method above, the LibraryManagerThread needs to know about the signals i am going to emit from the main GUI thread, hence it would then require code changes to use this class in a different application.

any thoughts how i could get around this?

cheers,

David

wysota
30th October 2009, 13:34
It doesn't need to know about the signals. It just needs to expose a set of slots conforming to the functionality it contains. The rest is left to the environment of the class that needs to connect those signals properly.

doggrant
30th October 2009, 13:43
Cool. So I make the connections to those public slots in my main GUI thread.

cheers :)

Corinzio
30th October 2009, 15:06
Why do you use moveToThread in the constructor? Do you use object created in another thread in your run method?

Thanks

doggrant
3rd November 2009, 15:49
To be honest, i'm not sure why i have this in there, I got the code from another example, and that is what it had.

My worker thread is coming along now and my gui is nice and smooth.

However i think i'm going to have to impleament some sort of thread pool for api calls.

At the moment i have one thread which queues all my calls into the blocking library, but when calls into this thread are in quick succession, this can be slow.