OpenHPI Course
Week 5 : Distributed Memory Parallelism
Unit 5.5: Programming with Actors
Dr. Peter Trger + Teaching Team
Actor Model
48
Concurrency in Erlang
50
Actors in Erlang
51
-module(tut15).
-export([test/0, ping/2, pong/0]).
[erlang.org]
Ping actor,
sending message to Pong
Blocking recursive receive,
scanning the mailbox
Pong actor
Blocking recursive receive,
scanning the mailbox
Actors in Scala
53
import scala.actors.Actor
import scala.actors.Actor._
case class Inc(amount: Int)
case class Value
class Counter extends Actor {
var counter: Int = 0;
def act() = {
while (true) {
receive {
case Inc(amount) =>
counter += amount
case Value =>
println("Value is "+counter)
exit()
}}}}
object ActorTest extends Application {
val counter = new Counter
counter.start()
for (i <- 0 until 100000) {
counter ! Inc(1)
}
counter ! Value
// Output: Value is 100000
}
OpenHPI | Parallel Programming Concepts | Dr. Peter Trger
Case classes,
acting as message types
Implementation of
the counter actor
Blocking receive loop,
scanning the mailbox
Actor Deadlocks
Synchronous send operator !? available in Scala
Sends a message and blocks in receive afterwards
Intended for request-response pattern
// actorA
actorB !? Msg1(value) match {
case Response1(r) =>
//
}
receive {
case Msg2(value) =>
reply(Response2(value))
}
// actorB
actorA !? Msg2(value) match {
case Response2(r) =>
//
}
receive {
case Msg1(value) =>
reply(Response1(value))
}
// actorB
actorA ! Msg2(value)
while (true) {
receive {
case Msg1(value) =>
reply(Response1(value))
case Response2(r) =>
// ...
}}
[http://savanne.be/articles/concurrency-in-erlang-scala/]
55