Lesson 42: Concurrency Models: Actors, CSP
In this lesson, we'll dive into two prominent concurrency models used in functional programming: Actors and Communicating Sequential Processes (CSP). Understanding these models will provide you with the tools needed to handle concurrent computations efficiently in functional programming languages.
The Actor Model
The Actor Model is a conceptual model that treats "actors" as the universal primitives of concurrent computation. In this model, actors can:
- Receive messages
- Send messages
- Create new actors
- Determine how to respond to the next message
Example in Akka (Scala)
Let's look at an example using Akka, a library for building actors in Scala:
import akka.actor._
case object Ping
case object Pong
class PingActor(pong: ActorRef) extends Actor {
def receive = {
case Ping =>
println("Ping received, sending Pong")
pong ! Pong
}
}
class PongActor extends Actor {
def receive = {
case Pong =>
println("Pong received, sending Ping")
sender() ! Ping
}
}
object ActorExample extends App {
val system = ActorSystem("PingPongSystem")
val pong = system.actorOf(Props[PongActor], name = "pongactor")
val ping = system.actorOf(Props(new PingActor(pong)), name = "pingactor")
ping ! Ping
}
Communicating Sequential Processes (CSP)
CSP is a formal language for describing patterns of interaction in concurrent systems. CSP emphasizes message passing over shared memory and uses channels to communicate between different processes.
Example in Go
Go's CSP model uses goroutines and channels to achieve concurrency:
package main
import (
"fmt"
"time"
)
func ping(pings chan<- string, msg string) {
pings <- msg
}
func pong(pings <-chan string, pongs chan<- string) {
msg := <-pings
pongs <- msg
}
func main() {
pings := make(chan string, 1)
pongs := make(chan string, 1)
go ping(pings, "Ping")
go pong(pings, pongs)
fmt.Println(<-pongs)
time.Sleep(1 * time.Second)
}
Actor Model vs. CSP
Both the Actor Model and CSP address the problem of concurrency but approach it differently:
- The Actor Model is about actors sending and receiving messages.
- CSP is about processes communicating over channels.
Understanding both models allows you to choose the right approach for your specific use case.
Refer to Wikipedia: Actor Model and Wikipedia: Communicating Sequential Processes for more in-depth information.