Skip to content

Instantly share code, notes, and snippets.

@temoto
Created December 14, 2010 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save temoto/741109 to your computer and use it in GitHub Desktop.
Save temoto/741109 to your computer and use it in GitHub Desktop.
package main
import (
"log"
"os"
)
func main() {
log.SetOutput(os.Stderr)
log.Print("Starting world")
world := newWorld()
log.Print("Spawning Mother Muh")
world.spawn("", "")
log.Print("Running simulation for 10 steps")
for i := 0; i < 10; i++ {
world.runStep()
}
}
# Muhs3 in Go.
include $(GOROOT)/src/Make.inc
TARG := muhs3
GOFMT := gofmt -spaces=true -tabindent=false -tabwidth=4
GOFILES := \
main.go \
muh.go \
world.go \
include $(GOROOT)/src/Make.cmd
format:
${GOFMT} -w ${GOFILES}
package main
import (
)
type Muh struct {
dna string
// State of a Muh organism
body string
links []*Muh
}
func newMuh(dna, body string) *Muh {
return &Muh {
dna: dna,
body: body,
links: make([]*Muh, 0),
}
}
package main
import (
"goconc.googlecode.com/hg"
"log"
"sync"
)
const DefaultConcurrency = 1000
type Stat struct {
generation int
}
type World struct {
pool []*Muh
stats map[*Muh] Stat
locks map[*Muh]*sync.Mutex
// World-update lock
lk *sync.Mutex
// Statistics
step int
}
func newWorld() *World {
return &World {
pool: make([]*Muh, 0),
stats: make(map[*Muh] Stat, 0),
locks: make(map[*Muh]*sync.Mutex, 0),
lk: new(sync.Mutex),
step: 0,
}
}
func (world *World) spawn(dna, body string) *Muh {
muh := newMuh(dna, body)
world.lk.Lock()
world.pool = append(world.pool, muh)
world.stats[muh] = Stat{generation: 1}
world.locks[muh] = new(sync.Mutex)
world.lk.Unlock()
return muh
}
func (world *World) runStep() {
max_concurrency := uint(DefaultConcurrency)
// In terms of Eventlet, this is a TokenPool.
// processMuh reserves an item from this channel,
// which limits max concurrent jobs.
limiter := make(chan bool, max_concurrency)
for i := uint(1); i <= max_concurrency; i++ {
limiter <- true
}
processMuh := func(item conc.Box) {
<-limiter
log.Print("processMuh")
muh := item.(*Muh)
log.Print("Processing Muh ", muh)
limiter <- true
}
world.step++
log.Print("World step #", world.step)
muhs := make(chan conc.Box)
wait := conc.For(muhs, processMuh)
for _, muh := range world.pool {
muhs <- muh
}
wait()
log.Print("checkpoint 1")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment