QT  - 讨论区

标题:Qt Tutorial 010:使用QtConcurrent 实现并发

2014年02月26日 星期三 09:22

为了充分发挥多核处理器的性能,我们经常需要在程序中使用并行计算的技术,让代码在多个CPU核心上同时运行。QtConcurrent提供了比常用的Thread更加高级的封装,也让编程更加简单和可靠。

The QtConcurrent namespace provides high-level APIs that make it possible to write multi-threaded programs without using low-level threading primitives such as mutexes, read-write locks, wait conditions, or semaphores. Programs written with QtConcurrent automatically adjust the number of threads used according to the number of processor cores available. This means that applications written today will continue to scale when deployed on multi-core systems in the future.

编程示例如下:

#include <QCoreApplication>
#include <QtConcurrent>
#include <QFuture>
#include <QDebug>
#include <QList>

int sum(int a,int b){
    QThread::sleep(3);
    return a+b;
}

void incr(int& i){
    i++;
}

bool is_odd(int i){
    if(i % 2 == 0){
        return false;
    } else {
        return true;
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QFuture<int> sumf =QtConcurrent::run(sum,100,200);
    qDebug() << sumf.isRunning();
    qDebug() << sumf.isFinished();
    sumf.waitForFinished();
    qDebug() << sumf.isFinished();
    qDebug() << sumf.result();

    QList<int> list;
    for(int i=0;i<10;i++){
        list.push_back(i);
    }
    auto mapf=QtConcurrent::map(list,incr);
    qDebug() << mapf.isFinished();
    mapf.waitForFinished();
    for(auto i : list){
        qDebug() << i;
    }

    auto filterf=QtConcurrent::filter(list,is_odd);
    qDebug() << filterf.isFinished();
    filterf.waitForFinished();
    qDebug() << filterf.isFinished();
    for(auto i : list) {
        qDebug() << i;
    }

    return a.exec();
}

参考资料:

http://qt-project.org/doc/qt-5.0/qtconcurrent/qtconcurrent.html

 

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2024

    京ICP备05028076号