我有這樣的功能
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;
我需要正確并行化這個函式。最好的方法是什么?
我是這樣寫的,但我不確定它是否正確:
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;
uj5u.com熱心網友回復:
// 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488410.html
