gpt4 book ai didi

scala - 当我们对 Scala Actor 使用循环而不是 while(true) 时会发生什么?

转载 作者:行者123 更新时间:2023-12-04 12:00:12 25 4
gpt4 key购买 nike

使用带有 Actor 的接收时使用循环而不是 while(true) 有什么区别。 Loop 似乎工作得更快,但为什么,引擎盖下发生了什么?

使用循环而不是 while(true) 有什么不好的吗?

更多关于上下文。我正在简单的 ping/pong 代码中进行性能测试。我正在使用接收。

这是 Ping 类:

class ReceivePing(
count : Int,
pong : Actor
) extends Actor {def act() {
var pingsLeft = count - 1
pong ! Start
pong ! ReceivePing
while(true) {
receive {
case ReceivePong =>
if (pingsLeft % 10000 == 0)
Console.println("ReceivePing: pong")
if (pingsLeft > 0) {
pong ! ReceivePing
pingsLeft -= 1
} else {
Console.println("ReceivePing: stop")
pong ! Stop
exit()
}
}
}}}

而不是 while(true) 它在循环中表现更好。

谢谢

最佳答案

while/receive循环 blocks a thread ,而 loop/react构造没有。这意味着第一个构造需要每个 actor 一个线程,这很快就会变慢。

根据 Haller and Odersky 2006 ,

An actor that waits in a receive statement is not represented by a blocked thread but by a closure that captures the rest of the actor's computation. The closure is executed once a message is sent to the actor that matches one of the message patterns specied in the receive. The execution of the closure is "piggy-backed" on the thread of the sender. If the receiving closure terminates, control is returned to the sender as if a procedure returns. If the receiving closure blocks in a second receive, control is returned to the sender by throwing a special exception that unwinds the receiver's call stack.



(显然他们后来改变了 receive 的行为并将旧的 receive 重命名为 react 。)

关于scala - 当我们对 Scala Actor 使用循环而不是 while(true) 时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4803801/

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