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
The while
/receive
loop blocks a thread, whereas the loop
/react
construct doesn't. This means the first construct needs one thread per actor, which quickly becomes slow.
According to 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.
(Apparently they later changed the behavior of receive
and renamed the old receive
to react
.)
Using loop
releases the thread to other tasks, while while
doesn't. So, if you are using many actors, the use of loop
makes then more efficient. On the other hand, a single actor using while
and receive
is much faster than one using loop
and react
(or, for that matter, loop
and receive
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With