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

爱⌒轻易说出口 提交于 2019-12-06 18:40:52

问题


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"?


回答1:


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.




回答2:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!