期货的实际用途?即,如何杀死它们? [英] Practical use of futures? Ie, how to kill them?

查看:35
本文介绍了期货的实际用途?即,如何杀死它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Future 非常方便,但在实践中,您可能需要对其执行进行一些保证.例如,考虑:

Futures are very convenient, but in practice, you may need some guarantees on their execution. For example, consider:

import scala.actors.Futures._

def slowFn(time:Int) = {
    Thread.sleep(time * 1000)
    println("%d second fn done".format(time))
}

val fs = List( future(slowFn(2)), future(slowFn(10)) )
awaitAll(5000, fs:_*)
println("5 second expiration. Continuing.")

Thread.sleep(12000)      // ie more calculations
println("done with everything")

这个想法是并行启动一些运行缓慢的函数.但是如果期货执行的函数不返回,我们不想永远挂起.所以我们使用 awaitAll() 为期货设置超时.但是,如果您运行代码,您会看到 5 秒计时器到期,但 10 秒未来会继续运行并稍后返回.超时不会扼杀未来;它只是限制了加入等待.

The idea is to kick off some slow running functions in parallel. But we wouldn't want to hang forever if the functions executed by the futures don't return. So we use awaitAll() to put a timeout on the futures. But if you run the code, you see that the 5 second timer expires, but the 10 second future continues to run and returns later. The timeout doesn't kill the future; it just limits the join wait.

那么你如何在超时后杀死一个未来?似乎期货不能在实践中使用,除非您确定它们会在已知的时间内返回.否则,您将面临将线程池中的线程丢失到非终止期货的风险,直到没有剩余的线程为止.

So how do you kill a future after a timeout period? It seems like futures can't be used in practice unless you're certain that they will return in a known amount of time. Otherwise, you run the risk of losing threads in the thread pool to non-terminating futures until there are none left.

所以问题是:你如何杀死期货?鉴于这些风险,期货的预期使用模式是什么?

So the questions are: How do you kill futures? What are the intended usage patterns for futures given these risks?

推荐答案

Future 旨在用于无论如何都需要等待计算完成的设置.这就是为什么它们被描述为用于运行缓慢的功能.您想要该函数的结果,但同时您还有其他事情可以做.事实上,您可能有许多 Future,它们彼此独立,您可能希望并行运行,同时等待所有 Future 完成.

Futures are intended to be used in settings where you do need to wait for the computation to complete, no matter what. That's why they are described as being used for slow running functions. You want that function's result, but you have other stuff you can be doing meanwhile. In fact, you might have many futures, all independent of each other that you may want to run in parallel, while you wait until all complete.

计时器只是提供等待以获得部分结果.

The timer just provides a wait to get partial results.

这篇关于期货的实际用途?即,如何杀死它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆