Threading a function in Qt
-
29-04-2021 - |
Question
I have a for-loop that will run a fixed number of times, usually in the 100-300 range depending on the input. Every iteration of this loop calls a function that I want to be threaded. The function to thread grabs data from an input file, does some stuff with it, then writes it out in a new format to an output file...
Here is some high-level code:
void myClass::processFile()
{
...
for (int index = 0; index < 200; index++)
{
//Function or loop to thread
generateData(someMapOfMaps1[index], someMapOfMaps2[index]);
}
}
Then inside generateData within the same class:
void myClass::generateData(QMap<float, foo*> mapA, QMap<float, foo*> mapB)
{
//read in data from a file
//process data
//write data to a different file
}
I played around with QtConcurrent::run()
and QtConcurrent::mapped()
but didn't have much luck. I believe mapped()
would have been a great choice, but my function takes 2 maps instead of just one.
I was using this as a resource, around slide 25: http://www.develer.com/promo/workshop/enhancing_with_multi_threading.pdf
Thanks!
Solution
- read this http://developer.qt.nokia.com/doc/qt-4.8/qwaitcondition.html
- inherit your class from
QThread
- put in
run()
call of your function in endless loop - stop loop by
QWaitCondition
before call generateData - wake up condition in your
for
cycle
OTHER TIPS
Put the loop, files read/write, 'some stuff', the lot in the thread. Trying to thread off one function call per loop is, well, just too much avoidable inter-thread comms. Pack the filespecs etc. into a myClass object, signal it to the thread and just let it go...