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

How to pass a function and its parameters to std::async, inside a member function

本文关键字:函数 std 成员 async 参数传递      更新时间:2023-10-16

我正在尝试通过以下方式在成员函数中使用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( 编译时出现以下错误:

..cppteststhreadsasync1main.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));

现场演示

我希望您知道execute函数正在阻塞,您不会通过在其中启动异步任务来获得任何利润。

相关文章: