Skip to content

Instantly share code, notes, and snippets.

@SimonRichardson
Created February 13, 2014 22:27
Show Gist options
  • Select an option

  • Save SimonRichardson/8985245 to your computer and use it in GitHub Desktop.

Select an option

Save SimonRichardson/8985245 to your computer and use it in GitHub Desktop.
PingPong actors in go
package main
import "fmt"
type Envelope struct {
message string
sender Actor
}
type Actor interface {
Id() int
Send(msg string, sender Actor)
Recieve()
}
type PingPongActor struct {
id int
mailbox chan Envelope
}
func (a *PingPongActor) Id() int {
return a.id
}
func (a *PingPongActor) Send(msg string, sender Actor) {
a.mailbox <- Envelope{msg, sender}
}
func (a *PingPongActor) Recieve() {
for {
select {
case env := <-a.mailbox:
fmt.Printf("* Actor %v recieved: %v from %v\n", a.id, env.message, env.sender.Id())
switch env.message {
case "Ping":
env.sender.Send("Pong", a)
case "Pong":
}
}
}
}
func spawn(id int) Actor {
channel := make(chan Envelope)
a := PingPongActor{id, channel}
go a.Recieve()
return &a
}
func main() {
actors := make([]Actor, 2, 2)
actors[0] = spawn(0)
actors[1] = spawn(1)
actors[0].Send("Ping", actors[1])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment