c++multithreadingqtqfuture

Qt calling threads in a loop


I have a code like this with function double myfunction(double) that takes a lot of time to finish.

Using Qt (https://doc.qt.io/qt-5/qtconcurrentrun.html), how can I run the loop utilizing a thread for every myfunction call to have smaller computation time? Does this make sense?

std::vector<double> parameters;        //vector full of input values
std::vector<double> results;           //vector to store results in

for(uint i=0; i<parameters.size(); i++)
{
   double parameter = parameters.at(i);
   double result = myfunction(parameter);
   results.push_back(result);
}

Solution

  • A simple example usage of QtConcurrent::run for you own case would be something like (untested)...

    std::vector<double> parameters;     // vector full of input values.
    std::vector<double> results;        // Empty vector to store results.
    
    /*
     * Each call to QtConcurrent::run returns a QFuture.  Store
     * these so we can wait on the results.
     */
    std::vector<QFuture<double>> futures;
    
    /*
     * Start all tasks and store the QFutures.
     */
    for (auto parameter: parameters) {
        futures.push_back(QtConcurrent::run(&myfunction, parameter));
    }
    
    /*
     * Wait for each QFuture in turn and save its result.
     */
    for (auto &f: futures) {
        results.push_back(f.result());
    }