Created
March 30, 2021 06:57
-
-
Save wirelessr/90c6906caad4a6bd243c726c73f1a592 to your computer and use it in GitHub Desktop.
Leetcode concurrency #1226 The Dining Philosophers (in golang)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type DiningPhilosophers struct { | |
wg *sync.WaitGroup | |
n int | |
forks [5]sync.Mutex | |
ate [5]int | |
} | |
func (obj *DiningPhilosophers) checkAll() bool { | |
end := true | |
for i := 0 ; i < len(obj.ate) ; i++ { | |
if obj.ate[i] < obj.n { | |
end = false | |
} | |
} | |
return end | |
} | |
func (obj *DiningPhilosophers) wantsToEat(philosopher int) { | |
defer obj.wg.Done() | |
leftHand := philosopher | |
var rightHand int | |
if rightHand = philosopher - 1 ; rightHand < 0 { | |
rightHand += 5 | |
} | |
for { | |
var end bool | |
if leftHand > rightHand { | |
obj.forks[rightHand].Lock() | |
fmt.Printf("[%d,2,1]\n", philosopher) | |
obj.forks[leftHand].Lock() | |
fmt.Printf("[%d,1,1]\n", philosopher) | |
obj.ate[philosopher]++ | |
fmt.Printf("[%d,0,3]\n", philosopher) | |
end = obj.checkAll() | |
obj.forks[leftHand].Unlock() | |
fmt.Printf("[%d,1,2]\n", philosopher) | |
obj.forks[rightHand].Unlock() | |
fmt.Printf("[%d,2,2]\n", philosopher) | |
} else { | |
obj.forks[leftHand].Lock() | |
fmt.Printf("[%d,1,1]\n", philosopher) | |
obj.forks[rightHand].Lock() | |
fmt.Printf("[%d,2,1]\n", philosopher) | |
obj.ate[philosopher]++ | |
fmt.Printf("[%d,0,3]\n", philosopher) | |
end = obj.checkAll() | |
obj.forks[rightHand].Unlock() | |
fmt.Printf("[%d,2,2]\n", philosopher) | |
obj.forks[leftHand].Unlock() | |
fmt.Printf("[%d,1,2]\n", philosopher) | |
} | |
if end { | |
return | |
} | |
} | |
} | |
func run(n int) { | |
wg := &sync.WaitGroup{} | |
obj := DiningPhilosophers{wg: wg, n :n} | |
wg.Add(5) | |
for i := 0; i < 5; i++ { | |
go obj.wantsToEat(i) | |
} | |
wg.Wait() | |
} | |
func main() { | |
run(1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment