Skip to content

Instantly share code, notes, and snippets.

@artur-kink
Created September 14, 2014 02:45
Show Gist options
  • Save artur-kink/d3285f04fc0cf63a7bc3 to your computer and use it in GitHub Desktop.
Save artur-kink/d3285f04fc0cf63a7bc3 to your computer and use it in GitHub Desktop.
A simple shell program for a step by step walkthrough of a bankers algorithm.
package main
import "fmt"
import "math/rand"
import "time"
func main() {
var resources = 3
resource_totals := make([]int, resources)
rand.Seed(time.Now().UTC().UnixNano())
for r := 0; r < resources; r++ {
resource_totals[r] = rand.Intn(5) + 5
}
var processes = 4
processes_maximum := make([][]int, processes)
for i := range processes_maximum {
processes_maximum[i] = make([]int, resources)
for r := 0; r < resources; r++ {
processes_maximum[i][r] = rand.Intn(5)
}
}
processes_current := make([][]int, processes)
for i := range processes_current {
processes_current[i] = make([]int, resources)
}
fmt.Println("Number of resources: ", resources)
for {
//Display current state
fmt.Println("\nResource totals: ", resource_totals)
fmt.Println("Process maximum requirements: ", processes_maximum)
fmt.Println("Process current usage: ", processes_current)
//Get a processes request
var process int
fmt.Print("Request's process#: ")
fmt.Scanf("%d", &process)
request := make([]int, resources)
for i := 0; i < resources; i++ {
fmt.Print("Request's resource #", i, " amount: ")
fmt.Scanf("%d", &request[i])
}
fmt.Println("Request Resources: ", request);
//Check if request is valid
valid := true
resource_current := make([]int, resources)
for r := 0; r < resources; r++ {
for p := 0; p < processes; p++ {
resource_current[r] += processes_current[p][r]
}
//More than available resources requested
if resource_current[r] + request[r] > resource_totals[r] {
fmt.Println("Invalid request, exceeds available total resources.")
valid = false
break
}
}
if valid {
valid = false
for p := 0; p < processes; p++ {
for r := 0; r < resources; r++ {
if (resource_totals[r] - resource_current[r]) + processes_current[p][r] >= processes_maximum[p][r] {
//There is enough resources to fulfill this resource.
valid = true;
}else{
//This process cannot be satisfied.
valid = false;
break;
}
}
if valid == false {
break
}
}
if valid {
fmt.Println("Request is valid.")
//Apply request
full := true;
for r := 0; r < resources; r++ {
processes_current[process][r] += request[r]
if full && processes_current[process][r] != processes_maximum[process][r] {
full = false
}
}
if full {
for r := 0; r < resources; r++ {
processes_current[process][r] = 0
}
}
}else{
fmt.Println("Request is invalid.")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment