Skip to content

Instantly share code, notes, and snippets.

@gcmurphy
Created December 12, 2012 05:25
Show Gist options
  • Save gcmurphy/4265073 to your computer and use it in GitHub Desktop.
Save gcmurphy/4265073 to your computer and use it in GitHub Desktop.
Rough attempt to implement Actor in Go based on Gevent tutorial example here: http://sdiehl.github.com/gevent-tutorial/#actors
package main
import (
"time"
)
type Action func(interface{})
type Actor struct {
Inbox chan interface{}
Stop chan bool
Action Action
}
func NewActor() *Actor {
return &Actor{
make(chan interface{}),
make(chan bool),
nil,
}
}
func (a *Actor) Start() {
go func() {
for {
select {
case msg := <-a.Inbox:
a.Action(msg)
case <-a.Stop:
return
}
}
}()
}
func pinger(a *Actor) {
a.Inbox <- "ping"
}
func ponger(a *Actor) {
a.Inbox <- "pong"
}
func main() {
ping := NewActor()
pong := NewActor()
ping.Action = func(msg interface{}) {
println(msg.(string))
time.Sleep(50 * time.Millisecond)
go pinger(pong)
}
pong.Action = func(msg interface{}) {
println(msg.(string))
time.Sleep(50 * time.Millisecond)
go ponger(ping)
}
ping.Start()
pong.Start()
ping.Inbox <- "Start"
done := make(chan bool)
go func() {
<-time.After(1 * time.Second)
ping.Stop <- true
pong.Stop <- true
done <- true
}()
<-time.After(250 * time.Millisecond)
println("1/4 there!")
<-time.After(250 * time.Millisecond)
println("1/2 there!")
<-time.After(250 * time.Millisecond)
println("3/4 there!")
<-done
println("done!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment