vendredi 9 août 2019

How to pass a function and its parameters to std::async

I'm trying to use std::async inside a member function in the following way:

#include <iostream>
#include <vector>
#include <string>
#include <future>

using namespace std;

class splitter
{
    public:
    splitter() = default;
    virtual ~splitter() = default;
    bool execute(vector<string> &vstr);
    bool split_files(vector<string> &vstr);
};

bool splitter::split_files(vector<string> &vstr)
{
    for(auto & file : vstr)
    {
        // do something
        cout << file << endl;
    }
    return true;
}

bool splitter::execute(vector<string> &vstr)
{
    auto fut = std::async(std::launch::async, split_files, vstr);
    bool good = fut.get();
    return good;
}

int main()
{
    vector<string> filenames {
                                "file1.txt",
                                "file2.txt",
                                "file3.txt"
                             };

    splitter split;
    split.split_files(filenames);

    return 0;
}

I would like to use std::async inside a member function to execute another member function in a separate thread, which takes a vector of strings as a parameter.
compiling with gcc (9.1) I get the following error:

..\cpp\tests\threads\async1\main.cpp|29|error: no matching function 
for call to 
'async(std::launch, <unresolved overloaded function type>, 
std::vector<std::__cxx11::basic_string<char> >&)'|

Aucun commentaire:

Enregistrer un commentaire