我有两个Scala函数,运行起来很昂贵。每个变量都如下所示,它们开始提高变量的值,我想在5分钟(或其他时间)之后同时运行它们。我想终止这两个功能,并取其到那时的最新价值。
def func1(n: Int): Double = {
var a = 0.0D
while (not terminated) {
/// improve value of 'a' with algorithm 1
}
}
def func2(n: Int): Double = {
var a = 0.0D
while (not terminated) {
/// improve value of 'a' with algorithm 2
}
}
我想知道我应该如何构造我的代码,以及什么是最佳实践?我正在考虑在两个具有超时的不同线程中运行它们,并在超时时返回它们的最新值。但是似乎还有其他方法可以做到这一点。我是Scala的新手,所以任何见解都将大有帮助。
不难。这是一种实现方法:
@volatile var terminated = false
def func1(n: Int): Double = {
var a = 0.0D
while (!terminated) {
a = 0.0001 + a * 0.99999; //some useless formula1
}
a
}
def func2(n: Int): Double = {
var a = 0.0D
while (!terminated) {
a += 0.0001 //much simpler formula2, just for testing
}
a
}
def main(args: Array[String]): Unit = {
val f1 = Future { func1(1) } //work starts here
val f2 = Future { func2(2) } //and here
//aggregate results into one common future
val aggregatedFuture = for{
f1Result <- f1
f2Result <- f2
} yield (f1Result, f2Result)
Thread.sleep(500) //wait here for some calculations in ms
terminated = true //this is where we actually command to stop
//since looping to while() takes time, we need to wait for results
val res = Await.result(aggregatedFuture, 50.millis)
//just a printout
println("results:" + res)
}
但是,当然,您可能希望查看while循环并创建更可管理和可链接的计算。
输出: results:(9.999999999933387,31206.34691883926)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句