Just getting started on Scala Actors. The Scala website says:
Thread-blocking operations can be avoided by using
react
to wait for new messages (the event-based pendant ofreceive
). However, there is a (usually small) price to pay:react
never returns....
Note that using
react
inside awhile
loop does not work! However, since loops are common there is special library support for it in form of aloop
function. It can be used like this:
loop {
react {
case A => ...
case B => ...
}
}
I'm now confused - there seems to be a contradiction:
a) If react
never returns, then what's the point of putting it in a loop?
b) Since loop
repeatedly executes a block, how is it any different to while(true)
- why doesn't while
work, and in what way does it "not work"?
Both functions, loop
and react
are not pure. loop
takes a call by name parameter and react
a PartialFunction, both set variables on the raw actor. This is because an actor does not have a thread attached all the time. It will become active only when there is a message in it's messagebox. This is why a while(true)
will lead to 100% cpu usage and the actor not responding.
I found an explanation that answers part a) of my question, in one of Haller and Odersky's papers on Actors (my emphasis below):
The central idea is as follows: 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.
A necessary condition for the scheme to work is that receivers never return normally to their enclosing actor. In other words, no code in an actor can depend on the termination or the result of a receive block...
来源:https://stackoverflow.com/questions/9704696/scala-actors-if-react-never-returns-why-does-it-need-to-be-in-a-loop-and-wh