当我们在 scala actor 中使用循环而不是 while(true) 时会发生什么?
在与 actor 一起使用 receive 时,使用循环而不是 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),它的性能更好。
谢谢
What's the difference of using loop instead of while(true) while using receive with actors. Loop seems to work much faster, but why, and what's going on under the bonnet?
Is there anything bad to use loop instead of while(true)?
More about context. I'm doing performance tests within simple ping/pong code. And I'm using receive.
This is the Ping class:
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()
}
}
}}}
instead of while(true) it performs better with loop.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
while
/receive
循环阻塞线程< /a>,而loop
/react
构造则不然。这意味着第一个构造需要每个参与者一个线程,这很快就会变得很慢。根据 Haller 和 Odersky 2006,
(显然他们后来改变了
receive
的行为,并将旧的receive
重命名为react
。)The
while
/receive
loop blocks a thread, whereas theloop
/react
construct doesn't. This means the first construct needs one thread per actor, which quickly becomes slow.According to Haller and Odersky 2006,
(Apparently they later changed the behavior of
receive
and renamed the oldreceive
toreact
.)使用
loop
会将线程释放给其他任务,而while
则不会。因此,如果您使用许多参与者,那么使用loop
可以提高效率。另一方面,使用while
和receive
的单个参与者比使用loop
和react
的参与者要快得多(或者,就此而言,循环
和接收
)。Using
loop
releases the thread to other tasks, whilewhile
doesn't. So, if you are using many actors, the use ofloop
makes then more efficient. On the other hand, a single actor usingwhile
andreceive
is much faster than one usingloop
andreact
(or, for that matter,loop
andreceive
).