I’ve written some library code (in C) to facilitate creating and querying threads independent of the platform. Here’s a psuedo-code example of the API to create a thread:
result OS_createThread (
pointer to thread handle (set after thread is created),
stack size,
function to run,
pointer to parameters,
priority )
Depending on the platform, I use the appropriate c file that contains the particular OS implementation to kick off the thread. E.g.
result OS_createThread (
// Windows implementation
map priority to Windows priority
// Use Win32 threading call
CreateThread(blah blah)
I’ve created ports for Win32, POSIX threads, and some RTOSes I’ve used. Now I need to do this for a Qt environment and I’m a little stumped. First off, I’m a Qt newbie, second it looks like it will require an object oriented approach using the QThread class.
The point of this is to hide the guts of the thread creation to the caller. The caller wants to be able to kick off threads and maintain a handle to that thread so that it can do things in the future like change its priority or kill it.
Using QThreads, does a new QThread object need to be created each time a new thread is requested? Keep in mind that the calling code cannot have anything Qt-specific.
Any guidance is appreciated!
To create a QThread you would implement a class inheriting from QThread. Example taken from the QT Documentation
And hidden in your implementation would be:
So your C interface method would create an instance of such a class for each thread being requested. This class should then store all the relevant data passed from your function within its member variables. The thread function to be executed would be called within the
run()method. Since you seem to execute only C methods I see no problem storing a pointer to them within a class variable (please correct me anyone if I’m wrong – haven’t tried it yet ;).However, its actually a bit more tricky than that, because somebody will have to free the memory created for the
threadvariable. And thats not easily (from a C interface) possible with my example. So you might want to think about using an internal manager class or something that handles the created threads and destroys them as needed. In order to make a qualified statement about how you could achieve this, however, I’d need a bit more information 😉