之前一直很少用到條件變量蒸殿,最近看了看筷厘,順便嘗試寫(xiě)了寫(xiě)哲學(xué)家就餐問(wèn)題挽铁。
問(wèn)題描述
如圖,五個(gè)哲學(xué)家圍著圓桌吃意面敞掘,每位哲學(xué)家或者拿起左右手邊的叉進(jìn)食叽掘,或者放回兩邊的叉思考。經(jīng)典的死鎖問(wèn)題玖雁。
Code
package main
import (
"fmt"
"sync"
"time"
)
type philosopher struct {
id int
eating bool
left *philosopher
right *philosopher
table *sync.Mutex
cond *sync.Cond
}
func (p *philosopher) run() {
for {
p.think()
p.eat()
}
}
func (p *philosopher) think() {
p.table.Lock()
p.eating = false
p.left.cond.Signal()
p.right.cond.Signal()
p.table.Unlock()
fmt.Printf("==philosopher %d Think\n", p.id)
time.Sleep(time.Second) // 根據(jù)需要改成sleep隨機(jī)時(shí)間
}
func (p *philosopher) eat() {
p.table.Lock()
for p.left.eating || p.right.eating {
p.cond.Wait()
}
p.eating = true
p.table.Unlock()
fmt.Printf(" philosopher %d Eat\n", p.id)
time.Sleep(time.Second) // 根據(jù)需要改成sleep隨機(jī)時(shí)間
}
func main() {
var table sync.Mutex
var pher [5]philosopher
for i := 0; i < 5; i++ {
pher[i].id = i + 1
pher[i].left, pher[i].right = &pher[(i+4)%5], &pher[(i+1)%5]
pher[i].table = &table
pher[i].cond = sync.NewCond(&table)
}
for i := 0; i < 5; i++ {
go pher[i].run()
}
// 無(wú)限等待
var wg sync.WaitGroup
wg.Add(1)
wg.Wait()
}
作者原創(chuàng)更扁,轉(zhuǎn)載請(qǐng)注明出處