What does function eventloop
do in Scala Actors and what is it useful for?
eventloop
works similarly to loop
and react
being combined. The difference between loop
and eventloop
is that loop
, in fact, doesn't call the body recursively (to prevent stack overflow for thread-based actors), but schedules handling (react/receive) of a next message from the mailbox, and finishes execution of a current handler throwing an exception, to clear up the call stack.
eventloop
recursively handles the messages using react
- in case of react
it's safe (and stack doesn't get overflown), because the body of react
(but not receive
!) always ends with an exception, in the most cases, and the next loop scheduled, to guarantee a fair access to the thread pool form all actors. Therefore, eventloop
can be used only with event-driven actors.
import scala.actors._
import Actor._
class EventLoop extends Actor {
def act = eventloop{
case msg => println("Received " + msg)
}
}
Maybe this thread can give some details:
One important motivation for actors is that they allow you to avoid control inversion meaning that there is at most one thread executing inside an actor at a time, and the user chooses when this is going to happen by writing a straight-line program that waits for messages at explicit points in the control flow.
In this model, one usually wants to avoid passing callback functions out to other threads that invoke them asynchronously; instead, other threads should interact with an actor only by sending messages to it. If callback-like behavior is wanted then the following pattern achieves it in a thread-safe manner:
def eventloop() {
react {
case Event1 =>
// handle Event1
eventloop()
...
case Eventn =>
// handle Eventn
eventloop()
} }
This pattern is provided as an abstract operation in
Actor.eventloop
:
import scala.actors.Actor._
eventloop {
case Event1 =>
// handle Event1
case Eventn =>
// handle Eventn
}
Note that there is no need for tail calls to some enclosing function any more.
That being said, considering the thread dates from 2008, and the Scala Actor API guide doesn't mention eventloop
once, maybe this not used that often.
Vasil Remeniuk expertly details eventloop
usage in his answer (+1) and gives a concrete example in the question "Client-Server example with Scala actors".
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