【问题标题】:Using std::async in constructor在构造函数中使用 std::async
【发布时间】:2016-10-13 20:30:47
【问题描述】:

我对 C++11 功能 std::async 还很陌生,我无法理解为什么下面的代码从不打印 bar

有人可以帮我解释一下吗?

class Thready {

  public:

    Thready() {
        std::async(std::launch::async, &Thready::foo, this);
    }

    void foo() {
        while (true) {
            std::cout << "foo" << std::endl;
        }
    }

    void bar() {
        while (true) {
            std::cout << "bar" << std::endl;
       }
    }
};

int main() {  
    Thready t;
    t.bar();
}

【问题讨论】:

    标签: multithreading c++11 stdasync


    【解决方案1】:

    请参阅此页面上的“注释”部分:http://en.cppreference.com/w/cpp/thread/async

    实现可以扩展第一个重载的行为 std::async 通过在 默认启动策略。实现定义的启动示例 策略是同步策略(立即执行,在异步 调用)和任务策略(类似于异步,但线程本地不是 清除) 如果从 std::async 获得的 std::future 没有从 或绑定到引用,std::future 的析构函数将阻塞 在完整表达式的末尾,直到异步操作 完成,本质上使如下代码同步:

    std::async(std::launch::async, []{ f(); }); // temporary's dtor waits for f()
    std::async(std::launch::async, []{ g(); }); // does not start until f() completes
    

    (注意 std::futures 的析构函数 通过调用 std::async 以外的方式获得永远不会阻塞)

    TL;DR:

    尝试将 std::async 调用的返回值保存到某个变量中:

    auto handle = std::async(std::launch::async, &Thready::foo, this);
    

    编辑:

    以下代码应该可以按预期工作。

    #include <future>
    #include <iostream>
    
    class Thready {
    
      public:
    
        Thready() {
            handle = std::async(std::launch::async, &Thready::foo, this);
        }
    
        void foo() {
            while (true) {
                std::cout << "foo" << std::endl;
            }
        }
    
        void bar() {
            while (true) {
                std::cout << "bar" << std::endl;
           }
        }
    
        std::future<void> handle;
    };
    
    int main() {  
        Thready t;
        t.bar();
    }
    

    【讨论】:

    • 很好,有道理。是否有可能使它在 foo 无效的情况下工作?
    • 是的,请参阅编辑。显然,这种情况有一个模板专门化,std::future&lt;void&gt;。它甚至还有void get() 方法!不过我从来没用过。
    猜你喜欢
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 2022-11-20
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多