简体   繁体   English

std ::带有临时std :: promise的未来

[英]std::future with temporary std::promise

I have a problem with understanding how the promise cooperates with future. 我在理解诺言如何与未来合作方面存在问题。 I have a function that is returning std::future like in this example: 我有一个返回std::future的函数,例如以下示例:

std::future<int> calcSomeValue() {
}

My problem is that this future can be either calculated asynchronously spawning a thread, or can have a result already ready to return, so I would like to have it returned using std::promise without running a thread. 我的问题是,可以通过异步生成线程来计算此未来,或者可以已经准备好返回结果,因此我想使用std::promise将其返回而不运行线程。 But... I don't know if this is safe or not or what else could I do. 但是...我不知道这是否安全或者我还能做什么。 See example: 参见示例:

std::future<int> calcSomeValue() {
    if (resultIsReady()) {
        std::promise<int> promise; // on the stack
        std::future<int>  rv = promise.get_future(); // is future part of the memory occupied by promise?

        promise.set_value(resultThatIsReady); // does it store the value in promise or in future?
        return rv; // <--- What will happen when promise is lost?
    }
    else {
        return std::async(....)
    }
}

See the comment in the code above. 请参阅上面的代码中的注释。 Is future accessing promise variable when .get() is called, where promise is already fulfilled? 调用.get()时已经实现诺言的将来访问诺言变量吗? If it is then I will have a big doo doo here. 如果是的话,我在这里会有一个大的斗。

Can anyone advise me how can I return std::future in this particular case? 谁能告诉我在这种情况下如何返回std::future

A promise -object is associated with a shared state (note the "shared"). 一个promise与一个共享状态相关联(请注意“共享”)。 When calling promise::get_future , you'll receive a future - object associated with the same shared state as the one with which the respective promise object is associated. 当调用promise::get_future ,您会收到一个future -具有相同的共享状态与各自的承诺对象相关联的一个相关物品。 This state will live at least as long as one associated producer (ie the promise) or a consumer (ie the future) lives. 该状态的生存时间至少与一个关联的生产者(即承诺)或消费者(即未来)的寿命相同。 Hence, it does not matter if the promise 's lifetime ends before the corresponding future -object. 因此, promise的生存期是否在相应的future之前结束并不重要。

Not normative, but see, for example, promise as described at cplusplus.com: 不规范的,但是见,例如, 承诺如在cplusplus.com描述:

The lifetime of the shared state lasts at least until the last object with which it is associated releases it or is destroyed. 共享状态的生存期至少要持续到与之关联的最后一个对象释放它或销毁它为止。 Therefore it can survive the promise object that obtained it in the first place if associated also to a future. 因此,如果它也与未来相关联,那么它可以幸免最初获得它的诺言对象。

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

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