Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Actors: if react never returns, why does it need to be in a loop{}, and why doesn't while(true) work?

Tags:

scala

actor

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 of receive). However, there is a (usually small) price to pay: react never returns.

...

Note that using react inside a while loop does not work! However, since loops are common there is special library support for it in form of a loop 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"?

like image 392
DNA Avatar asked Mar 14 '12 15:03

DNA


1 Answers

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.

like image 173
drexin Avatar answered Nov 01 '22 20:11

drexin