0

我假设我缺少一些非常简单的东西std::async。我正在尝试void异步运行 2 个方法,没有返回值。

#include <future>

class AsyncTestClass {

    public:
        void Initialize()
        {
            std::async(&AsyncTestClass::AsyncMethod1);
            std::async(&AsyncTestClass::AsyncMethod2);
        }

        void AsyncMethod1()
        {
            //time consuming operation
        }

        void AsyncMethod2()
        {
            //time consuming operation
        }
};

但是在调用 my AsyncMethod1or AsyncMethod2within时会出错std:async

替换失败:type 'typename std:conditional<sizeof....(ArgTypes) == 0, std::_Invoke_traits_Zero<void, typename std::decay .....is ill forms with _Fty = void (AsyncTestClass:: *)(), _ArgTypes =

std:asyncvoid参数方法的正确用法是什么?我看到的示例似乎与我使用它的方式相似,但它对我不起作用。

4

1 回答 1

3

AsyncTestClass::AsyncMethod1,作为非静态成员函数,只能在AsyncTestClass提供的实例时调用。你可能是这个意思:

std::async(&AsyncTestClass::AsyncMethod1, this)

这将创建一个std::future对象,其值将通过评估获得this->AsyncMethod1()

顺便说一句,std::async应该将返回值赋给一个变量,否则调用会阻塞。请参阅std::async 在未存储返回值时不会产生新线程。如果你有 C++20,编译器会为你捕捉到这个,这要感谢[[nodiscard]].

于 2021-01-15T02:10:49.513 回答