我有这样的功能
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;
发布于 2022-06-09 07:56:06
// 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://stackoverflow.com/questions/72555442
复制相似问题