gpt4 book ai didi

scala - 需要澄清 Scala 中的 future 和 promise

转载 作者:行者123 更新时间:2023-12-04 22:49:34 24 4
gpt4 key购买 nike

我试图了解 Scala 的 promise 和 future 的构造。

我一直在阅读Futures and Promises在 Scala 文档中,我有点困惑,因为我感觉 promise 和 future 的概念是混在一起的。

In my understanding a promise is a container that we could populate value in a later point. And future is some sort of an asynchronous operation that would complete in a different execution path.



在 Scala 中,我们可以使用附加的回调来获得结果。

我迷失的地方是 promise 如何拥有 future ?

我也在 Clojure 中阅读过这些概念,假设 promise 和 future 有一些通用的通用概念,但似乎我错了。

A promise p completes the future returned by p.future. This future is specific to the promise p. Depending on the implementation, it may be the case that p.future eq p.


val p = promise[T]
val f = p.future

最佳答案

您可以将 future 和 promise 视为管道的两个不同侧面。
在promise端,数据被插入,在future端,数据可以被拉出。

And future is some sort of an asynchronous operation that would complete in a different execution path.



实际上,future 是一个值的占位符对象,它可能在某个时间点异步可用。它不是异步计算本身。

有一个名为 future 的 future 构造函数的事实返回这样一个占位符对象并产生完成此占位符对象的异步计算并不意味着异步计算称为 future 。还有其他 future constructors/factory methods .

But the point I do not get is how promise has a future?



将 Promise 和 Futures 划分为 2 个独立的接口(interface)是一个设计决策。你可以在同一个界面下拥有这两个 Future ,但这将允许 future 的客户完成它们,而不是 future 的预期完成者。这将导致意外错误,因为可能有任意数量的竞争完成者。

例如。 future 产生的异步计算构造时,它是否必须完成 promise ,或者客户是否会这样做,将不再是明确的。

future 和 promise 旨在约束程序中的数据流。
这个想法是让 future 的客户端订阅数据以在数据到达后对其进行操作。
Promise 客户端的作用是提供该数据。
混合这两个角色可能会导致程序更难理解或推理。

您可能还会问为什么 Promise特征不扩展 Future .这是阻止程序员盲目传递 Promise 的另一个设计决定。 s 给客户,他们应该在哪里上传 PromiseFuture (这种向上转换很容易被忽略,而必须明确调用 future 以确保您每次都调用它)。换句话说,通过返回一个 promise ,您将有权完成它给其他人,通过返回 future ,您将有权订阅它。

编辑:

如果您想了解更多关于 future 的信息,《学习 Scala 中的并发编程》一书的第 4 章详细介绍了它们。免责声明:我是本书的作者。

关于scala - 需要澄清 Scala 中的 future 和 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18960339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com