Skip to content

Instantly share code, notes, and snippets.

@kidoman
Last active December 23, 2015 14:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kidoman/6647055 to your computer and use it in GitHub Desktop.
Save kidoman/6647055 to your computer and use it in GitHub Desktop.
My attempt at a "Dining Philosophers" simulation using Go concurrency Play version at: http://play.golang.org/p/Cy0ReZARbK
// Dining Gophers^2
// - By Karan
package main
import (
"flag"
"log"
"runtime"
"time"
)
const FORK = 1
var (
gomaxprocs = flag.Int("procs", runtime.NumCPU(), "how many (civilized) gophers on the table")
count = flag.Int("count", 3, "how many gophers")
eatingTime = flag.Int64("delay", 300, "how many ms do the gophers take to eat")
runTime = flag.Int64("time", 5, "how many seconds to run simulation")
thinkTime = flag.Int64("think", 200, "how many ms to think")
)
func gopher(i int, lp chan int, rp chan int) {
for {
// The first gopher is Rocky Balboa
strongPaw, weakPaw := lp, rp
if i > 0 {
strongPaw, weakPaw = rp, lp
}
// Grab fork in strong paw
<-strongPaw
// Grab fork in weak paw
<-weakPaw
log.Printf("Gopher %v eating\n", i+1)
time.Sleep(time.Duration(*eatingTime) * time.Millisecond)
log.Printf("Gopher %v stopped eating\n", i+1)
// Give the forks back
lp <- FORK
rp <- FORK
log.Printf("Gopher %v thinking\n", i+1)
time.Sleep(time.Duration(*thinkTime) * time.Millisecond)
log.Printf("Gopher %v stopped thinking\n", i+1)
}
}
func main() {
flag.Parse()
if *count < 2 {
log.Fatalln("Count has to be a minimum of 2")
}
runtime.GOMAXPROCS(*gomaxprocs)
// Let there be forks
forks := make([]chan int, *count)
for i := 0; i < *count; i++ {
f := make(chan int, 1)
go func(f chan<- int) { f <- FORK }(f)
forks[i] = f
}
// Gopher run!
go gopher(0, forks[0], forks[len(forks)-1])
for i := 0; i < len(forks)-1; i++ {
go gopher(i+1, forks[i+1], forks[i])
}
// Run simulation
time.Sleep(time.Duration(*runTime) * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment