This question already has answers here:
Passing arguments to std::async by reference fails
                                
                                    (3个答案)
                                
                        
                                4个月前关闭。
            
                    
我正在尝试通过以下方式在成员函数内使用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;
}


我想在成员函数内使用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> >&)'|

最佳答案

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

因为split_files是成员函数,所以您需要传递将在其上调用此函数的this

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


Live demo

我希望您知道execute函数正在阻塞,通过在其中启动异步任务不会有任何好处。

关于c++ - 如何在成员函数内部将函数及其参数传递给std::async ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57427740/

10-11 22:43
查看更多