gpt4 book ai didi

multithreading - Scala:WAITING列表被填充

转载 作者:行者123 更新时间:2023-12-04 06:43:58 24 4
gpt4 key购买 nike

假设有一个列表,其中存储了分布式计算的作业结果。

现在我有一个主线程正在等待所有作业完成。

我知道在所有工作完成之前需要有 List 的大小。
Scala 中让主线程(while(true) 循环)休眠并在作业完成时唤醒它的最优雅方式是什么?

谢谢你的回答

编辑:好的,在尝试了@Stefan-Kunze 的概念但没有成功(我猜我没有明白这一点......)我举了一个带有一些代码的例子:

第一个节点:

class PingPlugin extends SmasPlugin
{
val messages = new ListBuffer[BaseMessage]()

val sum = 5

def onStop = true

def onStart =
{
log.info("Ping Plugin created!")

true
}

def handleInit(msg: Init)
{
log.info("Init received")

for( a <- 1 to sum)
{
msg.pingTarget ! Ping() // Ping extends BaseMessage
}

// block here until all messages are received
// wait for messages.length == sum

log.info("handleInit - messages received: %d/%d ".format(messages.length, sum))


}

/**
* This method handles incoming Pong messages
* @param msg Pong extends BaseMessage
*/
def handlePong(msg: Pong)
{
log.info("Pong received from: " + msg.sender)
messages += msg

log.info("handlePong - messages received: %d/%d ".format(messages.length, sum))
}
}

第二个节点:
class PongPlugin extends SmasPlugin
{
def onStop = true

def onStart =
{
log.info("Pong Plugin created!")
true
}

/**
* This method receives Ping messages and send a Pong message back after a random time
* @param msg Ping extends BaseMessage
*/
def handlePing(msg: Ping)
{
log.info("Ping received from: " + msg.sender)
val sleep: Int = math.round(5000 * Random.nextFloat())
log.info("sleep: " + sleep)

Thread.sleep(sleep)
msg.sender ! Pong()
}
}

我想解决方案是可能的 future ......

最佳答案

选择@jilen 的方法:(此代码假设您的结果是结果类型)

//just like lists futures can be yielded
val tasks: Seq[Future[Result]] = for (i <- 1 to results.size) yield future {
//results.size is the number of //results you are expecting
println("Executing task " + i)
Thread.sleep(i * 1000L)
val result = ??? //your code goes here
result
}


//merge all future results into a future of a sequence of results
val aggregated: Future[Seq[Result]] = Future.sequence(tasks)


//awaits for your results to be computed
val squares: Seq[Int] = Await.result(aggregated, Duration.Inf)
println("Squares: " + squares)

关于multithreading - Scala:WAITING列表被填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20602257/

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