Skip to content

Instantly share code, notes, and snippets.

@sideb0ard
Created November 18, 2014 15:53
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 sideb0ard/bb7b89284a654d7defc4 to your computer and use it in GitHub Desktop.
Save sideb0ard/bb7b89284a654d7defc4 to your computer and use it in GitHub Desktop.
Dining Philosoraptors with Channels as Semaphores
package main
import (
"fmt"
"math/rand"
"time"
)
type Philosopher struct{}
var philosophers [5]Philosopher
var forks [5]chan int
var done = make(chan int)
func main() {
for i := range forks {
forks[i] = make(chan int)
}
for p := range philosophers {
fmt.Println("Philosoraptor", p, "starts thinking..")
go philosophers[p].philosophy(p)
}
for i := range forks {
forks[i] <- 1
}
<-done
}
func (p Philosopher) philosophy(num int) {
fmt.Println("yow, i'm", num, "philosophiszing...")
for {
fmt.Println("Serious time , P", num, "thinking for a bit...")
p.randy() // think
fmt.Println("Eating time , P", num, "grabbing forks...")
if num == 4 {
p.Fork(num, "grab", "right")
p.Fork(num, "grab", "left")
} else {
p.Fork(num, "grab", "left")
p.Fork(num, "grab", "right")
}
fmt.Println("Nom NOM, P", num, "eating for a bit...")
p.randy() // eat
fmt.Println("DUn Eating time , P", num, "releasing forks...")
if num == 4 {
p.Fork(num, "release", "right")
p.Fork(num, "release", "left")
} else {
p.Fork(num, "release", "left")
p.Fork(num, "release", "right")
}
}
}
func (p Philosopher) randy() {
rand.Seed(time.Now().Unix())
//time.Sleep(time.Duration(rand.Intn(5)) * time.Millisecond)
time.Sleep(time.Duration(rand.Intn(5)) * time.Second)
}
func (p Philosopher) Fork(num int, action string, fork string) {
fmt.Println("fork", action, fork, "for philosopher", num)
n := num
if fork == "right" {
n = (num + 1) % len(forks)
}
if action == "grab" {
<-forks[n]
fmt.Println("Oh, got sumping from channel", n, "for", fork)
} else if action == "release" {
forks[n] <- 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment