c++multithreadingqtqthreadqtconcurrent

How to put my function into a thread Qt Concurrent


I have function like this

QList<MyObject*> list;

for (int i = 0; i < count; ++i)
{
    auto *object = new MyObject(this);
    ProcessFunc1(object);
    ProcessFunc2(object);
    
    ProcessFunc3(object); // a heavy function that I would like to parallelize

    list.push_back(object);
}

return list;

I need to correctly parallelize this function. What is the best way to do it?

I wrote it like this, but I'm not sure it's correct:

QList<MyObject*> list;
QFutureSynchronizer<MyObject*> syncronizer;
for (int i = 0; i < count; ++i)
{
    auto future = QtConcurrent::run([this]() -> MyObject* {
        auto *object = new MyObject(this);
        ProcessFunc1(object);
        ProcessFunc2(object);
    
        ProcessFunc3(object); // a heavy function that I would like to parallelize
        return object;
});
    syncronizer.addFuture(future);
}

syncronizer.waitForFinished();

for (int i = 0; i < syncronizer.futures().count(); ++i)
    list.push_back(syncronizer.futures().at(i).result());

return list;

Solution

  • // create the objects in the main thread:
    // creating objects in another thread can result in pain,
    // see e.g. https://doc.qt.io/qt-6/qobject.html#thread-affinity
    QList<MyObject *> list;
    for (int i = 0; i < count; ++i)
        list.emplaceBack(this); // equivalent to list.append(new MyObject(this))
    // "map" (== "apply") your function to all objects in parallel, wait for the result
    QtConcurrent::blockingMap(list, [] {
        ProcessFunc1(object);
        ProcessFunc2(object);
        ProcessFunc3(object);
    });
    // here everything is done, since blockingMap waits for everything to finish