如何将函数及其参数传递给成员函数内的 std::async
How to pass a function and its parameters to std::async, inside a member function
我正在尝试通过以下方式在成员函数中使用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
函数正在阻塞,您不会通过在其中启动异步任务来获得任何利润。
相关文章:
- 无法引用该函数" std:: variant <_Types...> operator =",因为此函数已被删除
- 错误:使用已删除的函数"std::unique_ptr<...>
- 我有模板功能.通过使用函数std::for_each,用这个容器中的最大数字替换每个正数
- 如何使用函数std::min()来计算最小值
- 删除了 g++ 在 linux 中basic_stringstream函数 std
- 如何在 c++ 中使用返回类型导出函数 std::map
- 错误:使用已删除的函数"std::atomic<_Tp>::atomic() [_Tp = node]"
- 使用 SFINAE 检查函数 std::to_string 是否存在类型
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误
- 为什么函数 std::basic_streambuf::setg() 需要非常量 agruments
- C++将已删除的函数 std::unique_ptr 与基类一起使用
- 奇怪的错误:当没有真正创建指针时,使用已删除的函数'std::unique_ptr<_Tp,_Dp>::unique_ptr
- 通过模板构造函数(std ::功能和迷你案例)将构造函数触发
- 错误:使用已删除的函数"std::atomic<_Tp>::atomic()
- 错误:使用已删除的函数std::basic_ofstream(OpenCV和C++11)
- 类成员容器迭代器在成员函数std::find中不兼容,但为什么不兼容呢
- 没有构造函数 std::istream_iterator 的实例
- 错误:没有与参数列表匹配的重载函数"std::make_shared"实例
- 错误:使用已删除的函数"std::thread::thread(const std::thread&)"
- 不能在没有对象的情况下调用成员函数 std::string class::function()