这周课程设计,以为会很好玩,实验书发下来,居然只是实现银行家算法,失望了……用了小半天时间(原谅我上过 *** 作系统居然连银行家算法是什么都忘了,只能回去看书重来),用golang简单实现了银行家算法,一下是代码:
package mainimport ( "fmt" "log" "os")var Available []int //可以用资源向量var Max [][]int //最大需求矩阵var Allocation [][]int //已分配矩阵var Need [][]int //需求矩阵var Request []int //请求向量var Work []int //工作向量var Finish []bool //Finish向量var pID int //请求资源进程号var serial []int //用于存储安全序列var work [][]int//初始化func init() { //资源数量为10,5,7 //资源数量为10,7}//银行家算法func Bank() { for i := 0; i < len(Request); i++ { if Request[i] <= Need[pID][i] { continue } else { log.Fatalln("所需资源超过宣布最大值") } } for i := 0; i < len(Request); i++ { if Request[i] <= Available[i] { continue } else { log.Fatalln("尚无足够资源,需等待") } } for i := 0; i < len(Available); i++ { Available[i] = Available[i] - Request[i] } for i := 0; i < len(Allocation[0]); i++ { Allocation[pID][i] = Allocation[pID][i] + Request[i] } for i := 0; i < len(Need[0]); i++ { Need[pID][i] = Need[pID][i] - Request[i] } if Safe() { fmt.Println("完成分配") } else { fmt.Println("系统处于不安全状态,等待") } fmt.Println("Max:",Max) fmt.Println("Allocation:",Allocation) fmt.Println("Need:",Need) fmt.Println("Available:",Available) fmt.Println("Work:",work) fmt.Println("安全序列:",serial)}//安全性检查func Safe() bool { Work = Available for i := 0; i < len(Max); i++ { Finish = append(Finish,false) } temp := 0step2: for i := temp; i < len(Finish); i++ { if Finish[i] == false { for j := 0; j < len(Work); j++ { if Need[i][j] <= Work[j] { if j == len(Work)-1 { serial = append(serial,i) work = append(work,Work) for j := 0; j < len(Work); j++ { Work[j] = Work[j] + Allocation[i][j] } Finish[i] = true if i == len(Finish)-1 { temp = 0 } else { temp = i + 1 } goto step2 } } else { break } } } else { continue } if i == len(Finish)-1 { return false } } return true}func main() {lable: var sel int fmt.Println("********************银行家算法********************") fmt.Println() fmt.Println("\t1、测试数据一") fmt.Println("\t2、测试数据二") fmt.Println("\t3、测试数据三") fmt.Println("\t4、退出") fmt.Println() fmt.Println("************************************************") fmt.Print("请做出你的选择:") fmt.Scanln(&sel) switch sel { //资源总数量为10,7 case 1: //测试数据1 Available = []int{3, 3, 2} Max = [][]int{{7, 5, 3},{3, 2, 2},{9, 0,{2,{4, 3}} Allocation = [][]int{{0, 1, 0}, 1},{0, 2}} Need = [][]int{{7, 4,{1,{6, 1}} Request = []int{1, 2} pID = 1 case 2: //测试数据2 Available = []int{2, 0} Max = [][]int{{7, 1}} Request = []int{3, 0} pID = 4 case 3: //测试数据3 Available = []int{2, 1}} Request = []int{0, 0} pID = 0 case 4: os.Exit(0) default: fmt.Println("没有此选项") } //执行银行家算法 Bank() goto lable}
很简陋,只测试了三组数据,如果发现BUG,望斧正,谢谢!
总结以上是内存溢出为你收集整理的golang简单实现银行家算法全部内容,希望文章能够帮你解决golang简单实现银行家算法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)