QT下的并行框架

ConcurrentRun

for (auto layIdx = 0; layIdx != cli->layerCount(); ++layIdx)
{
    QFutureWatcher<bool>* watcher = new QFutureWatcher<bool>();
    QObject::connect(watcher, SIGNAL(finished()), this, SLOT(renderLayerFinshed()));
    QFuture<bool> future = QtConcurrent::run(this, &CppBackendWorker::renderLayersInConCurrent, cli, layIdx);
    watcher->setFuture(future);
}
void CppBackendWorker::renderLayerFinshed()
{
    m_layerCount = m_layerCount + 1;

    QFutureWatcher<bool>* watcher = static_cast<QFutureWatcher<bool>*>(sender());
    watcher->deleteLater();  // 信号的指针释放

    if (m_layerTotal == m_layerCount)
    {
        // 所有任务做完进行后续处理;
        QMetaObject::invokeMethod(m_backend, "finishRenderingLayers", Qt::QueuedConnection);
    }
}
1 Concurrent中允许传入当前类的成员函数,通常此函数是一个耗时函数,本例中为renderLayersInConcurrent.

2 注意watcher这些指针的释放,在单次任务结束后删除watcher指针。如果是QFutureWatcher<bool> watcher; 再绑定信号槽是无效的,在堆上而非栈上.


mappedReduced

struct layerResult
{
    Typedef QMap<int, bool>layerCount;   
    QString m_stErrorInfo;//   QString m_strTargetFilePath;//生成目标文件的路径全称   
    layerCount layercount;
};

class SingleLayerProcess;  // 处理耗时任务的类

// 单个任务的处理,将处理结束的结果存入layerRes中
layerResult createLayerDate(const SingleLayerProcess& layer)
{   
    layerCount layercount;   
    layerResult layerRes;      
    SingleLayerProcess layerTemp = const_cast<SingleLayerProcess&>(layer);   
    if (!layerTemp.createEntity()) //耗时任务
    {    
        …   
    }   
    if (!layerTemp.manageSharpAngleAndExtraShell())  //耗时任务 
    {       
        …   
    }   
    if (!layerTemp.createSingleLayerData()) //耗时任务
    {       
        …   
    }   
    layercount[layer.getLayerIndex()] = true;   
    layerRes.layercount=layercount;     
    return layerRes;
} 

// 单线程处理,获取单任务的结果,进行统一处理
void mergeLayer(layerResult&result,const layerResult&signalLayersRes)
{   
    …
} 

// 对多个类似任务进行批量处理
QList<SingleLayerProcess> layers;
for (int index = iBegin; index < iEnd; ++index)
{
    SingleLayerProcess singleLayer(index, pCliFile, fillingParamStruct, fillType, strTargetFilePath);
    layers.push_back(singleLayer);
}
layerResult layerRet = QtConcurrent::mappedReduced(layers, createLayerDate, mergeLayer, ReduceOptions(OrderedReduce | SequentialReduce));
1 在 QFuture<T>mappedReduced(const Sequence &sequence, MapFunction mapFunction, ReduceFunction reduceFunction, QtConcurrent::ReduceOptions reduceOptions = UnorderedReduce | SequentialReduce)中, Sequence可以是一个类的容器列表,可以创建一个处理耗时任务的类的list,此例中则是QList<SingleLayerProcess> layers.
2 MapFunction的返回值类型必须和reduceFunction的第2个参数相匹配,此例中则是layerResult类型
3 reduceFunction这一函数是任务队列进行结束的结果处理,单线程。你可以通过ReduceOptions控制得到结果的顺序。
4 只有mappedReduced可以进行cancle,concurrent::run不能进行cancle操作



已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页