Golang 写的一个动态时间片轮转进程调度算法
现在还有一个问题,在最后一个进程运行完之后,还会再打印一次输出
package main
import "fmt"
type Process struct { //定义进程的数据结构
PRIORITY int
CPUTIME int
ALLTIME int
STATE string
}
func main() {
PR := map[int]*Process{ //初始进程
0: &Process{
PRIORITY: 9,
CPUTIME: 0,
ALLTIME: 3,
STATE: "ready",
},
1: &Process{
PRIORITY: 38,
CPUTIME: 0,
ALLTIME: 2,
STATE: "ready",
},
2: &Process{
PRIORITY: 30,
CPUTIME: 0,
ALLTIME: 6,
STATE: "ready",
},
3: &Process{
PRIORITY: 29,
CPUTIME: 0,
ALLTIME: 3,
STATE: "ready",
},
4: &Process{
PRIORITY: 0,
CPUTIME: 0,
ALLTIME: 4,
STATE: "ready",
},
}
for ; ; { //无限循环
num := GetFirst(PR) //取出优先级最大的ID
GetReady(PR, num) //输出就绪队列
flag := ProcessController(PR, num) //进程控制,以及判断是否还有进程
if flag == 1{
break
}else {
continue
}
}
}
func GetReady(process map[int]*Process,num int) {
fmt.Printf("当前正在运行的进程: %d \n",num)
fmt.Println("当前就绪队列为:")
for k,_ := range process{
if k != num {
fmt.Print(k," ")
}else {
continue
}
}
fmt.Println()
}
func GetFirst(process map[int]*Process)(num int) { //找出优先级最高的进程
max := 0
num = 4
for k,_ := range process{
if process[k].PRIORITY > max{
max = process[k].PRIORITY
num = k
}else {
continue
}
}
return num
}
func ProcessController(process map[int]*Process,id int) (flag int) { //进程控制模块
if process[id] == nil{
fmt.Println("当前无可运行进程")
flag = 1
}else {
process[id].PRIORITY -= 3
process[id].ALLTIME -= 1
process[id].CPUTIME += 1
if process[id].ALLTIME == 0 {
delete(process, id)
}
flag = 0
}
return flag
}