QtConcurrent记录

等待返回处理后的结果

int function(const int &a)
{
    qDebug() << __LINE__ <<  __FUNCTION__ << __FILE__<<QThread::currentThreadId();
    return a*100;
}
 QList<int> list{0,1,2,3};
   auto f  = QtConcurrent::blockingMapped(list,function);
   for (auto& v:f) {
       qDebug() << __LINE__ <<  __FUNCTION__ << __FILE__<<v;
   }

返回处理后的结果

  QList<int> list{0,1,2,3};
    auto f  = QtConcurrent::mapped(list,function);
    f.waitForFinished();
    for (auto& a: f.results()) {
        qDebug() << __LINE__ <<  __FUNCTION__ << __FILE__<<a;
    }

直接修改原队列

void function(int &a)
{
    qDebug() << __LINE__ <<  __FUNCTION__ << __FILE__<<QThread::currentThreadId();
     a = a*100;
}
QList<int> list{0,1,2,3};
    auto f  = QtConcurrent::map(list,function);
    f.waitForFinished();
    for (auto& a: list) {
        qDebug() << __LINE__ <<  __FUNCTION__ << __FILE__<<a;
    }

将结果继续传递给新函数,并在新函数里再处理成一个单值

新函数必须是“V function(T &result,const U &intermediate)”的形式

int function(const int &a)
{
    return  a*100;
}

void reduce(int& result,const int& in)
{
    result += in ;
}

void Widget::on_pushButton_clicked()
{
    QList<int> list{0,1,2,3};
    auto f  = QtConcurrent::mappedReduced(list,function,reduce);
    f.waitForFinished();
    qDebug() << __LINE__ <<  __FUNCTION__ << __FILE__<<f.result();
}

可以使用成员函数

 QStringList lst;
    lst<<"123"<<"456"<<"789";
    auto f1 = QtConcurrent::blockingMappedReduced(lst,&QString::length,strLength);
    qDebug() << __LINE__ <<  __FUNCTION__ << __FILE__<<f1;

输出

9
 auto f2 = QtConcurrent::blockingMappedReduced(lst,&QString::length,&QList<int>::push_back);

输出

(3, 3, 3)

支持函数对象

struct strExpand
{
    strExpand(int a):m_a{a}{}
    typedef QString result_type;//
    QString operator()(const QString& str)
    {
        return  str + QString::number(m_a);
    }
    int m_a{0};
};
 QStringList lst;
    lst<<"123"<<"456"<<"7899";
auto f3  = QtConcurrent::mapped(lst,strExpand{10086});
    f.waitForFinished();
    qDebug() << __LINE__ <<  __FUNCTION__ << __FILE__<<f3.results();

bind

int fun(int b,const int& a)
{
    return  a+1+b;
}

QList<int> list{0,1,2,3};
    auto bFun = std::bind(&fun,100,std::placeholders::_1);
    auto f  = QtConcurrent::mappedReduced(list,bFun,reduce);
    f.waitForFinished();
    qDebug() << __LINE__ <<  __FUNCTION__ << __FILE__<<f.result();

过滤

bool aselect(const int& value)
{
    return  value%2;
}
  auto f11  = QtConcurrent::filtered(list,aselect);
    f11.waitForFinished();

run

 QtConcurrent::run([]{
        qDebug() << __LINE__ <<  __FUNCTION__ << __FILE__<<QThread::currentThreadId();
    });
  QFuture<bool> f =  QtConcurrent::run(this,&Widget::threadTest,1024);

QFutureWatcher 观察并发结束

 m_watcher.setFuture(f);
    qDebug() << __LINE__ <<  __FUNCTION__ << __FILE__;
    connect(&m_watcher,&QFutureWatcherBase::finished,this,[&]{
        qDebug() << __LINE__ <<  __FUNCTION__ << __FILE__<<m_watcher.result();
    });

你可能感兴趣的:(Qt,qt)