简体   繁体   English

反复调用std :: future :::

[英]calling std::future::get repeatedly

I want to construct an object Delay asynchronously and then (from another thread) repeatedly call a function foo from that object. 我想异步构造一个对象Delay ,然后(从另一个线程)反复从该对象调用函数foo

struct Delay {
    Delay(int d) {
        sleep(d);
    }
    void foo() { }
};

struct Test {
    Test() {
        x = async(std::launch::async,
                  [&]() {return std::make_unique<Delay>(4);});
    }
    void run() { x.get()->foo(); }
    std::future<std::unique_ptr<Delay>> x;
};

int main() {
    auto t = Test();
    // do other stuff...
    t.run();
    t.run(); // throwing an instance of 'std::future_error',  "No associated state"
    return 0;
}

However, obviously, the second time x.get() gets called, an exception is thrown. 但是,显然,第二次调用x.get()会引发异常。

What is the recommended way to deal with such a situation? 建议如何处理这种情况? Using a flag as shown below seems like a hack. 使用如下所示的标志似乎很容易。 Is there a better way? 有没有更好的办法?

bool is_set = false;
std::unique_ptr<Delay> ptr;
void run_ptr() {
    if (!is_set) {
        ptr = x.get();
        is_set = true;
    }
    ptr->out();
}

std::shared_future is the recommended way to deal with such a situation. 建议使用std::shared_future处理这种情况。

It can be constructed by moving from a future, and supports multiple readers of its state. 它可以从未来发展而来,并支持其状态的多个读者。 It is a distinct object because the one-deliver future had certain performance improvements, and because it is so trivial to make a shared future if you need it. 这是一个截然不同的对象,因为“一站交付”的未来具有一定的性能改进,并且如果需要的话,实现共享的未来也很简单。

Simply change the type of x to shared_future<std::unique_ptr<Delay>> and you are done. 只需将x的类型更改为shared_future<std::unique_ptr<Delay>> ,就可以完成。

Note, however, that in your above case the unique_ptr layer is mostly pointless. 但是请注意,在上述情况下, unique_ptr层几乎没有意义。 Probably in your real problem it is not. 可能不是您真正的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM