2
go 哲学家吃饭问题,请指教,谢谢。
source link: https://studygolang.com/articles/35296
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
go 哲学家吃饭问题,请指教,谢谢。
VacancyS · 大约22小时之前 · 94 次点击 · 预计阅读时间 2 分钟 · 大约8小时之前 开始浏览附上本人写的代码
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()
}
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:701969077
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK