What makes an "eventloop" function in Scala Actors?

What does the eventloop function in Scala Actors do and what is it useful for?

+7
source share
2 answers

eventloop works similarly to loop and react . The difference between loop and eventloop is that loop does not, in fact, call the body recursively (to prevent stack overflows for thread-based entities), but plans to process (respond / receive) the next message from the mailbox and terminate the current handler throwing an exception to clear the call stack.

eventloop recursively processes messages with react - in the case of react it is safe (and the stack does not overflow), because the body of the react (but not receive !) always ends except, in most cases, and the next loop planned to guarantee fair access to a pool of threads from all participants. Therefore, eventloop can only be used with event-based entities.

 import scala.actors._ import Actor._ class EventLoop extends Actor { def act = eventloop{ case msg => println("Received " + msg) } } 
+9
source

Maybe this thread can give some details:

One of the important motives for actors is that they allow you to avoid control inversion, which means that there is no more than one thread executing inside an actor at a time, and the user chooses when this happens by writing a straightforward program that waits for messages in explicit control flow points.

In this model, you usually want to avoid passing callback functions to other threads that call them asynchronously; instead, other threads should interact with the actor only by sending him messages. If the opposite behavior is required, then the following pattern reaches it in a thread-safe manner :

  def eventloop() { react { case Event1 => // handle Event1 eventloop() ... case Eventn => // handle Eventn eventloop() } } 

This template is presented 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 longer any need for tail calls of any closing function.


If we talk about the date of the stream since 2008, and the Scala Guide for the Actor API does not mention eventloop once, maybe this is often not used.
Vasily Remenyuk expertly describes eventloop using his answer (+1) and gives a concrete example in the question " Example client-server with Scala participants .

+3
source

All Articles