0

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.execute(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> >&)'|
Sergio
  • 891
  • 9
  • 27

1 Answers1

6

Use std::ref to pass vstr by reference.

Because split_files is member function you need to pass this on which this function will be called.

auto fut = std::async(std::launch::async, &splitter::split_files, this, std::ref(vstr));

Live demo

I hope you are aware that execute function is blocking, you don't have any profit by starting async task inside it.

rafix07
  • 20,001
  • 3
  • 20
  • 33