简体   繁体   中英

What does function “eventloop” do in Scala Actors?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM