附上本人写的代码
package main
import (
"fmt"
"sync"
"time"
)
const N = 5
type philosopher struct {
signal int
state [N]string
}
var ps [N]philosopher
var take sync.Mutex
var statep sync.Mutex
func thinking(i int) {
fmt.Printf("哲学家%d,正在思考问题\n", i)
time.Sleep(1 * time.Second)
}
func eating(i int) {
fmt.Printf("哲学家%d,正在吃饭\n", i)
time.Sleep(1 * time.Second)
}
func take_forks(i int) bool {
take.Lock()
defer take.Unlock()
statep.Lock()
ps[i].state[i] = "hungry"
statep.Unlock()
test_take_all_forks(i)
if ps[i].signal <= 0 {
return false
} else {
ps[i].signal--
return true
}
}
func test_take_all_forks(i int) {
statep.Lock()
defer statep.Unlock()
if ps[i].state[i] == "hungry" && ps[(i-1+N)%N].state[(i-1+N)%N] != "eating" && ps[(i+1+N)%N].state[(i+1+N)%N] != "eating" {
ps[i].state[i] = "eating"
ps[i].signal++
}
}
func put_forks(i int) {
take.Lock()
defer take.Unlock()
statep.Lock()
ps[i].state[i] = "thinking"
statep.Unlock()
test_take_all_forks((i - 1 + N) % N)
test_take_all_forks((i + 1 + N) % N)
}
func sophereating(i int) {
for {
thinking(i)
flag := take_forks(i)
if flag {
eating(i)
put_forks(i)
}
fmt.Printf("所有哲学家的状态\n")
for key, data := range ps {
fmt.Printf("%d %s \t", key, data.state[key])
}
fmt.Printf("\n")
}
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
statep.Lock()
ps[i].state[i] = "thinking"
ps[i].signal = 0
statep.Unlock()
}
wg.Add(1)
for i := 0; i < 5; i++ {
go sophereating(i)
}
wg.Wait()
}
有疑问加站长微信联系(非本文作者)