Search code examples
c++multithreadingqtqtconcurrent

QtConcurrent Map Cannot Use Class Method


Hello I am trying to pass QList to QtConcurrent::Map function, but it fails to start and I don't understand why, maybe some one knows what might be the problem?

This is the Class Method Code

void MainWindow::find_file(QStringList &lst){
    QString fl_name = ui->ln_FlName->text();
    QRegExp exp;
    exp.setPattern(".*/("+ui->ln_FlName->text()+").*");
    QRegExp exp_2;
    exp.setPattern(".*/("+ui->ln_FlName->text()+")");
     foreach(const QString &str,lst)
      {
        // Do some work...   
      }}

And this is the code when I try to execute this method

void MainWindow::on_btn_start_clicked(){
QDir start_path(ui->ln_Dir->text());
QList<QFuture<QStringList> > future_list;
QList<QStringList> dirs_lists;
QStringList temp_dir_list;
QList<QString> lst_str;
foreach(const QFileInfo fl_inf,start_path.entryInfoList(QDir::NoDotAndDotDot|QDir::Dirs))
{
    if(fl_inf.isDir())
    {
        //Here I use QtConcurrent::run with other method and it works fine

        QFuture<QStringList>ft;
        ft=QtConcurrent::run(this,&MainWindow::File_Search,fl_inf.filePath());
        future_list.append(ft);
        num_ft+=1;
        temp_dir_list.append(fl_inf.filePath());
        lst_str.append(fl_inf.filePath());
    }


}
dirs_lists.append(temp_dir_list);
long long int sum = 0;
for(int i=0;i<future_list.count();i++)
{

    sum += future_list.at(i).result().count();
    dirs_lists.append(future_list.at(i).result());
}


//But this doesn't want to work 

QFutureWatcher<void> ft_watcher;
ft_watcher.setFuture(QtConcurrent::map(dirs_lists,&MainWindow::find_file));
}

And the compiler outputs this errors:

error: no matching function for call to 'map(QList&, )' QtConcurrent::map(dirs_lists,MainWindow::find_file); ^

And

error: no match for call to '(QtConcurrent::MemberFunctionWrapper1) (QStringList&)' map(*it); ^


Solution

  • You're treating find_file as if it was a static method, not an instance method. There are two solutions:

    1. Turn find_file into a static method.

    2. Pass an instance to map: QtConcurrent::map(dirs_lists, &MainWindow::find_file, this).

    In either case, you must design find_file to be thread-safe, of course.