Tuesday, August 17, 2010

Basic usage of actors in scala

Summary:
This article gives a short introduction about parallel programming using scala actors.


 
The Scala programming language makes it easy to execute tasks in parallel. The easiest way to start parallel execution is to call the actor method of the Actor companion Object. 


This method takes a code block as parameter and creates a new thread executing the code block.

actor {
  // code to be executed
}

Note for java developers: using scala style the brackets around the method arguments are omitted here. The code shown above is equivalent to

actor({
  // code to be executed
})

The following example shows a small scala script that creates two actors. Each of the actors says hello for five times. After having sayed hello each actor takes a break for a small time.

import scala.actors.Actor._ 
for (actorId <- 1 to 2) {
  actor {
    for (helloIndex <- 1 to 5) {
      printf("Actor %d says hello  %d times.\n", actorId, helloIndex)
      Thread.sleep(30)
    }
  }
}


To run this example simple start the scala interpreter in interactive mode and paste the code into the command line.
If i execute the above script i get the following output:

Actor 1 says hello  1 times.
Actor 1 says hello  2 times.
Actor 2 says hello  2 times.
Actor 2 says hello  3 times.
Actor 1 says hello  3 times.
Actor 2 says hello  4 times.
Actor 1 says hello  4 times.
Actor 2 says hello  5 times.
Actor 1 says hello  5 times.

As you can see the messages from the two actors appear intermixed because the actors are executed in parallel. 


If you want to run the example in eclipse simply create a scala object with a main method and run it as scala application.

import scala.actors.Actor._ 
object SimpleActorDemo {

  def main(args: Array[String]): Unit = {
    for (actorId <- 1 to 2) {
      actor {
        for (helloIndex <- 1 to 5) {
          printf("Actor %d says hello  %d times.\n",
             actorId, helloIndex)
        }
      }
    } 
  }
}


Did you find this article useful? Your comments are greatly appreciated.