我怎样才能将这个 std::function 传递给 std::async

How can I pass this std::function to std::async

我正在编写一段多线程代码,但我似乎无法将 std::function 对象传递给 std::async 函数。我确定我做错了什么,但我不知道那会是什么。因此,我准备了这段代码,希望知道的人可以帮助我。

测试 1 证明此 std::function 对象有效。
Test2 包含我想让它做的事情;只有我将函数对象包装成一个 lambda。
Test3 包含我想不通的例子。

std::function<void(AsyncFunctionExample&)> current_function;

void Test1() {
  current_function = &AsyncFunctionExample::Function1;
  while(current_function != nullptr)
    current_function(*this);
}

void Test2() {
  current_function = &AsyncFunctionExample::Function1;
  while(current_function != nullptr)
    const std::future<void> function_future = std::async([&](){current_function(*this);});
}

void Test3() {
  current_function = &AsyncFunctionExample::Function1;
  while(current_function != nullptr)
    const std::future<void> function_future = std::async(current_function, *this);
}

可以找到此示例的完整代码 here。 Whosebug 编辑器警告我不允许转储完整的代码文件,所以我在这里将其归结为它的要点。

我收到的编译器错误是:
没有匹配函数来调用 'async(std::function&, AsyncFunctionExample&)' const std::future function_future = std::async(current_function, *this);

这对我帮助不大。它基本上向我解释说没有与我的电话匹配的签名。但是我无法从这个错误中找出我调用的哪一部分是错误的,而且我不知道如何更改它才能正常工作。

您不能通过 std::async 传递引用,因为它需要复制值。您可以使用 std::ref:

来解决这个问题
const std::future<void> function_future = std::async(current_function, std::ref(*this));

或者只需将函数更改为:

std::function<void(AsyncFunctionExample*)> current_function;

那你可以直接传this

const std::future<void> function_future = std::async(current_function, this);