如何在成员函数内将函数及其参数传递给 std::async

Ser*_*gio 0 c++ c++11 c++14 c++17

我尝试std::async按以下方式在成员函数内部使用:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我想std::async在成员函数内部使用来在单独的线程中执行另一个成员函数,该函数采用字符串向量作为参数。
使用 gcc (9.1) 编译时出现以下错误:

..\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> >&)'|
Run Code Online (Sandbox Code Playgroud)

raf*_*x07 6

用于通过引用std::ref传递vstr

因为split_files是成员函数,所以您需要传递this将调用该函数的成员函数。

auto fut = std::async(std::launch::async, &splitter::split_files, this, std::ref(vstr));
Run Code Online (Sandbox Code Playgroud)

现场演示

我希望您知道该execute函数是阻塞的,在其中启动异步任务不会给您带来任何好处。