【问题标题】:How to use std::async with void method with no parameters?如何在没有参数的情况下将 std::async 与 void 方法一起使用?
【发布时间】:2021-04-20 02:15:55
【问题描述】:

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

#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
        }
};

但是在std:async 内调用我的AsyncMethod1AsyncMethod2 时会出错:

替换失败:type 'typename std:conditional

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

【问题讨论】:

    标签: c++ asynchronous future stdasync


    【解决方案1】:

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

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

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

    顺便说一下std::async的返回值应该赋值给一个变量,否则调用会阻塞。见std::async won't spawn a new thread when return value is not stored。如果你有 C++20,由于[[nodiscard]],编译器会帮你捕捉到这个。

    【讨论】:

    • 哦,太好了,我不知道 async 已经从 C++20 中添加了 [[nodiscard]]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 2022-11-15
    • 2012-08-24
    相关资源
    最近更新 更多