go 哲学家吃饭问题,请指教,谢谢。

VacancyS · · 749 次点击 · · 开始浏览    

附上本人写的代码

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

749 次点击  
加入收藏 微博
4 回复  |  直到 2021-12-30 20:21:46
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传