Banker's algorithm: Difference between revisions

(→‎{{header|Perl 6}}: use hypers for array operations, tidying)
 
(21 intermediate revisions by 11 users not shown)
Line 1:
{{draft task|Classic CS problems}}{{Wikipedia|Banker's algorithm}}
{{Wikipedia|Banker's algorithm}}
 
 
The '''Banker's algorithm''' is a [[wp:resource allocation|resource allocation]] and [[wp:deadlock|deadlock]] avoidance [[wp:algorithm|algorithm]] developed by [[wp:Edsger Dijkstra|Edsger Dijkstra]] that tests for safety by simulating the allocation of predetermined maximum possible amounts of all [[wp:resource (computer science)|resources]], and then makes a "s-state" check to test for possible deadlock conditions for all other pending activities, before deciding whether allocation should be allowed to continue.
 
==== Example input ====
 
Assuming that the system distinguishes between four types of resources, (A, B, C and D), the following is an example of how those resources could be distributed. ''Note that this example shows the system at an instant before a new request for resources arrives. Also, the types and number of resources are abstracted. Real systems, for example, would deal with much larger quantities of each resource.''
;Example input:
Assuming that the system distinguishes between four types of resources, (A, B, C and D), the following is an example of how those resources could be distributed.
 
''Note that this example shows the system at an instant before a new request for resources arrives.   Also, the types and number of resources are abstracted.   Real systems, for example, would deal with much larger quantities of each resource.''
 
Total resources in system:
Line 30 ⟶ 37:
P2 0 2 0 1
P3 0 1 4 0
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
{{todo|Python|Translate all Spanish texts to English}}
 
<syntaxhighlight lang="11l">V resources = Int(input(‘Cantidad de recursos: ’))
V processes = Int(input(‘Cantidad de procesos: ’))
V max_resources = input(‘Recursos máximos: ’).split_py().map(i -> Int(i))
 
print("\n-- recursos asignados para cada proceso --")
V currently_allocated = (0 .< processes).map(j -> input(‘proceso #.: ’.format(j + 1)).split_py().map(i -> Int(i)))
 
print("\n--- recursos máximos para cada proceso ---")
V max_need = (0 .< processes).map(j -> input(‘proceso #.: ’.format(j + 1)).split_py().map(i -> Int(i)))
 
V allocated = [0] * resources
L(i) 0 .< processes
L(j) 0 .< resources
allocated[j] += currently_allocated[i][j]
print("\nRecursos totales asignados : #.".format(allocated))
 
V available = (0 .< resources).map(i -> :max_resources[i] - :allocated[i])
print("Recursos totales disponibles: #.\n".format(available))
 
V running = [1B] * processes
V count = processes
L count != 0
V safe = 0B
L(i) 0 .< processes
I running[i]
V executing = 1B
L(j) 0 .< resources
I max_need[i][j] - currently_allocated[i][j] > available[j]
executing = 0B
L.break
I executing
print(‘proceso #. ejecutándose’.format(i + 1))
running[i] = 0B
count--
safe = 1B
L(j) 0 .< resources
available[j] += currently_allocated[i][j]
L.break
I !safe
print(‘El proceso está en un estado inseguro.’)
L.break
 
print("El proceso está en un estado seguro.\nRecursos disponibles: #.\n".format(available))</syntaxhighlight>
 
{{out}}
<pre>
Cantidad de recursos: 4
Cantidad de procesos: 3
Recursos máximos: 6 5 7 6
 
-- recursos asignados para cada proceso --
proceso 1: 1 2 2 1
proceso 2: 1 0 3 3
proceso 3: 1 2 1 0
 
--- recursos máximos para cada proceso ---
proceso 1: 3 3 2 2
proceso 2: 1 2 3 4
proceso 3: 1 3 5 0
 
Recursos totales asignados : [3, 4, 6, 4]
Recursos totales disponibles: [3, 1, 1, 2]
 
proceso 1 ejecutándose
El proceso está en un estado seguro.
Recursos disponibles: [4, 3, 3, 3]
 
proceso 2 ejecutándose
El proceso está en un estado seguro.
Recursos disponibles: [5, 3, 6, 6]
 
proceso 3 ejecutándose
El proceso está en un estado seguro.
Recursos disponibles: [6, 5, 7, 6]
</pre>
 
=={{header|C}}==
Line 35 ⟶ 123:
 
There are two <code>main()</code> functions to choose from (look for <code>#define BIG_EXAMPLE</code>), one is for task example, the other is a much heavier duty test case.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdbool.h>
 
Line 147 ⟶ 235:
 
return 0;
}</langsyntaxhighlight>
{{out|Input and Output}}
<pre>Enter the number of resources: 4
Line 197 ⟶ 285:
The process is in safe state.
Available vector: 8 5 9 7</pre>
 
=={{header|FreeBASIC}}==
{{trans|Kotlin}}
{{todo|Python|Translate all Spanish texts to English}}
<syntaxhighlight lang="freebasic">
Dim As Integer i, j, r, p
Input "Ingrese la cantidad de recursos: ", r
Input "Ingrese la cantidad de procesos: ", p
 
Print !"\nIngrese los recursos m ximos: ";
Dim As Integer maxRes(r)
For i = 1 To r
Input ; " ", maxRes(i)
Next i
 
Print !"\n\n-- recursos asignados para cada proceso --"
Dim As Integer curr(p, r)
For i = 1 To p
Print "proceso"; i; ":";
For j = 1 To r
Input ; " ", curr(i, j)
Next j
Print
Next i
 
Print !"\n\n--- recursos m ximos para cada proceso ---"
Dim As Integer maxReclam(p, r)
For i = 1 To p
Print "proceso"; i; ":";
For j = 1 To r
Input ; " ", maxReclam(i, j)
Next j
Print
Next i
 
Print !"\nRecursos totales asignados : ";
Dim As Integer recAsigad(r)
For i = 1 To p
For j = 1 To r
recAsigad(j) += curr(i, j)
Next j
Next i
For i = 1 To r
Print recAsigad(i); " ";
Next i
 
Dim As Integer recDispon(r)
Print !"\n\nRecursos totales disponibles: ";
For i = 1 To r
recDispon(i) = maxRes(i) - recAsigad(i)
Print recDispon(i); " ";
Next i
 
Dim As Boolean ejecutando(p)
For i = 1 To p
ejecutando(i) = True
Next i
 
Dim As Integer contar = p
Do While contar <> 0
Dim As Boolean seguro = False
For i = 1 To p
If ejecutando(i) Then
Dim As Boolean ejecuta = True
For j = 1 To r
If (maxReclam(i,j) - curr(i,j) > recDispon(j)) Then
ejecuta = False
Exit For
End If
Next j
If ejecuta Then
Color 11 : Print !"\n\nproceso"; i; !" ejecut ndose."
ejecutando(i) = False
contar -= 1
seguro = True
For j = 0 To r
recDispon(j) += curr(i,j)
Next j
Exit For
End If
End If
Next i
If Not seguro Then
Color 12 : Print !"\nLos procesos est n en un estado inseguro."
Exit Do
End If
Color 10: Print "El proceso est  en un estado seguro."
Color 7: Print "Recursos disponibles: ";
For i = 1 To r
Print recDispon(i); " ";
Next i
Loop
Sleep
</syntaxhighlight>
{{out}}
<pre>
Ingrese la cantidad de recursos: 4
Ingrese la cantidad de procesos: 3
 
Ingrese los recursos máximos: 6 5 7 6
 
-- recursos asignados para cada proceso --
proceso 1: 1 2 2 1
proceso 2: 1 0 3 3
proceso 3: 1 2 1 0
 
 
--- recursos máximos para cada proceso ---
proceso 1: 3 3 2 2
proceso 2: 1 2 3 4
proceso 3: 1 3 5 0
 
Recursos totales asignados : 3 4 6 4
 
Recursos totales disponibles: 3 1 1 2
 
proceso 1 ejecutándose.
El proceso está en un estado seguro.
Recursos disponibles: 4 3 3 3
 
proceso 2 ejecutándose.
El proceso está en un estado seguro.
Recursos disponibles: 5 3 6 6
 
proceso 3 ejecutándose.
El proceso está en un estado seguro.
Recursos disponibles: 6 5 7 6
</pre>
 
 
=={{header|Go}}==
Line 202 ⟶ 422:
 
This solution is more inspired by EWD-623 than WP. EWD-623, while it talks of finding a permutation of processes, notes that the "ordering effort" can be stopped as soon as the process requesting resources happens to be found satisfiable. The solution here attempts to make this finding as soon as possible by moving the process to the front of a list of unsatisfied processes. Also since the solved permutation of satisfied processes has no use, it is not kept which simplifies the algorithm a bit.
<langsyntaxhighlight lang="go">package bank
 
import (
Line 363 ⟶ 583:
perm[h] = perm[m]
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="go">package main
 
import (
Line 391 ⟶ 611:
fmt.Println("\nP3 request:")
fmt.Println(b.Request("P3", bank.RMap{"A": 1, "B": 2, "C": 1}))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 413 ⟶ 633:
The task description currently does not define the process being run. So we follow the example set by other implementations and have each process free all resources after successfully being run. Also, since this is a demo, we give a blow-by-blow description of what's happening as it runs.
 
<langsyntaxhighlight lang="j">bankrun=:1 :0
'MAX ALLOC TOTAL'=. y
todo=.(#ALLOC)#1
Line 441 ⟶ 661:
end.
echo 'DONE'
)</langsyntaxhighlight>
 
Definitions for task example:
 
<langsyntaxhighlight lang="j">max=: 3 3 2 2,1 2 3 4,:1 3 5 0
alloc=: 1 2 2 1,1 0 3 3,:1 2 1 0
total=:6 5 7 6
Line 452 ⟶ 672:
NB. left arg: newly available resources, right: previously available
NB. result: resources freed
run=: +</langsyntaxhighlight>
 
Example run:
 
<langsyntaxhighlight Jlang="j"> run bankrun max;alloc;total
currently available: 3 1 1 2
running process 0, allocating 2 1 0 1
Line 466 ⟶ 686:
running process 2, allocating 0 1 4 0
process 2 freeing 1 3 5 0
DONE</langsyntaxhighlight>
 
=={{header|Julia}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="julia">function queryprompt(query, typ)
print(query, ": ")
entry = uppercase(strip(readline(stdin)))
Line 535 ⟶ 755:
 
testbankers()
</langsyntaxhighlight>{{out}}
<pre>
Enter the number of resources: 4
Line 602 ⟶ 822:
{{trans|C}}
For simplicity, input checking is ignored:
<langsyntaxhighlight lang="scala">// version 1.1.4-3
 
fun main(args: Array<String>) {
Line 670 ⟶ 890:
println("\nAvailable Vector: ${avl.joinToString(" ")}")
}
}</langsyntaxhighlight>
 
Sample input/output:
Line 725 ⟶ 945:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module BankerAlgo {
Form 80, 44
Line 894 ⟶ 1,114:
End Sub
}
BankerAlgo</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Kotlin}}
<syntaxhighlight lang="nim">import sequtils, strformat, strutils, sugar
 
stdout.write "Enter the number of resources: "
let r = stdin.readLine().parseInt()
 
stdout.write "Enter the number of processes: "
stdout.flushFile()
let p = stdin.readLine().parseInt()
 
stdout.write "Enter Claim Vector: "
let maxRes = stdin.readLine().splitWhitespace().map(parseInt)
 
echo "Enter Allocated Resource Table:"
var curr = newSeqWith(p, newSeq[int](r))
for i in 0..<p:
stdout.write &"Row {i + 1}: "
curr[i] = stdin.readLine().splitWhitespace().map(parseInt)
 
echo "Enter Maximum Claim Table:"
var maxClaim = newSeqWith(p, newSeq[int](r))
for i in 0..<p:
stdout.write &"Row {i + 1}: "
maxClaim[i] = stdin.readLine().splitWhitespace().map(parseInt)
 
var alloc = newSeq[int](r)
for i in 0..<p:
for j in 0..<r:
alloc[j] += curr[i][j]
echo &"\nAllocated Resources: {alloc.join(\" \")}"
 
var avl = collect(newSeq, for i in 0..<r: maxRes[i] - alloc[i])
echo &"Available Resources: {avl.join(\" \")}"
 
var running = repeat(true, p)
var count = p
while count > 0:
var safe = false
for i in 0..<p:
if running[i]:
var exec = true
for j in 0..<r:
if maxClaim[i][j] - curr[i][j] > avl[j]:
exec = false
break
if exec:
echo &"\nProcess {i + 1} is executing."
running[i] = false
dec count
safe = true
for j in 0..<r: avl[j] += curr[i][j]
break
 
if not safe:
echo "The processes are in an unsafe state."
break
 
echo "\nThe process is in a safe state."
echo &"Available Vector: {avl.join(\" \")}"</syntaxhighlight>
 
{{out}}
<pre>Enter the number of resources: 4
Enter the number of processes: 5
Enter Claim Vector: 8 5 9 7
Enter Allocated Resource Table:
Row 1: 2 0 1 1
Row 2: 0 1 2 1
Row 3: 4 0 0 3
Row 4: 0 2 1 0
Row 5: 1 0 3 0
Enter Maximum Claim Table:
Row 1: 3 2 1 4
Row 2: 0 2 5 2
Row 3: 5 1 0 5
Row 4: 1 5 3 0
Row 5: 3 0 3 3
 
Allocated Resources: 7 3 7 5
Available Resources: 1 2 2 2
 
Process 3 is executing.
 
The process is in a safe state.
Available Vector: 5 2 2 5
 
Process 1 is executing.
 
The process is in a safe state.
Available Vector: 7 2 3 6
 
Process 2 is executing.
 
The process is in a safe state.
Available Vector: 7 3 5 7
 
Process 4 is executing.
 
The process is in a safe state.
Available Vector: 7 5 6 7
 
Process 5 is executing.
 
The process is in a safe state.
Available Vector: 8 5 9 7</pre>
 
=={{header|Perl}}==
{{trans|Perl 6Raku}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
 
my $P = 3; # Number of processes
my $R = 4; # Number of resources
 
my @avail = (3, 1, 1, 2); # Available instances of resource
Line 911 ⟶ 1,234:
# Function to find the system is in safe state or not
sub isSafe {
my($availwork, $maxm, $allot) = @_;
my $P = @$allot; # Number of processes
my $satisfied;
my $R = @need$work; # theNumber needof matrixresources
for my $i@unfinished = (0..$P-1) { x $P; # CalculatingMark needall ofprocesses eachas $Punfinished
my(@safeSeq,@need);
for my $j (0..$R-1) { # Need of instance = maxm instance - allocated instance
for my $i (0..$P-1) { $ # Calculating need[$i][$j] =of $$maxm[$i][$j]each - $$allot[$i][$j]process:
for my $j (0..$R-1) { # maxm instance - allocated instance
$need[$i][$j] = $$maxm[$i][$j] - $$allot[$i][$j]
}
}
my @finish = (0) x $P; # Mark all processes as unfinished
my @safeSeq = (0) x $P; # To store safe sequence
my @work = @$avail; # Make a copy of available resources
 
# While all processes are not finished or system is not in safe state
my $count = 0;
while ($count < $P) { # Find a process which is not finish and whose needs
# can be satisfied with current @work resources.
my $found = 0;
for my $p (0..$P-1) {
# First check ifWhile a process is not finished, if no, go for next condition
if ($finishunfinished[$p] == 0) {
# Check if for all resources of current P need is less than work
my $satisfied;
LOOP: for my $j (0..$R-1) {
for my $j (0..$R-1) {
$satisfied = $j;
last LOOP if $need[$p][$j] > $$work[$j]
}
# If all needs of p were satisfied.
if ($satisfied == $R-1) {
$$work[$_] += @$$allot[$p]->[$_] for 0..$R-1; # free the resources
$safeSeq[$count]say ='available $p;resources: ' . join ' ', # Add this process to safe sequence.@$work;
$finish[push @safeSeq, $p] = 1; # MarkAdd this pprocess to assafe finishedsequence
$unfinished[$p] = 1; # Mark this process as finished
$count += 1;
$found = 1
Line 958 ⟶ 1,279:
my($safe_state,$status_message) = isSafe(\@avail, \@maxm, \@allot);
say "Safe state? " . ($safe_state ? 'True' : 'False');
say "Message: $status_message";</langsyntaxhighlight>
{{out}}
<pre>Safeavailable state?resources: True4 3 3 3
available resources: 5 3 6 6
Message: Safe sequence is: 0 1 2</pre>
available resources: 6 5 7 6
 
Safe state? True
=={{header|Perl 6}}==
<lang perl6># Reference:
# https://www.geeksforgeeks.org/program-bankers-algorithm-set-1-safety-algorithm/
# based on the Python3 solution by Shubham Singh(SHUBHAMSINGH10)
 
my \P = 3 ; # Number of processes
my \R = 4 ; # Number of resources
 
my @avail = <3 1 1 2>; # Available instances of resource
my @maxm = <3 3 2 2>, <1 2 3 4>, <1 3 5 0>; # Maximum R that can be allocated to processes
my @allot = <1 2 2 1>, <1 0 3 3>, <1 2 1 0>; # Resources allocated to processes
 
# Function to find the system is in safe state or not
sub isSafe(\avail, \maxm, \allot) {
my @need = @maxm »-« @allot; # the need matrix
my @finish = 0 xx P; # Mark all processes as unfinished
my @safeSeq = 0 xx P; # To store safe sequence
my @work = avail; # Make a copy of available resources
 
# While all processes are not finished or system is not in safe state
my $count = 0;
while $count < P { # Find a process which is not finish and whose needs
# can be satisfied with current @work resources.
my $found = False;
for ^P -> \p {
# First check if a process is finished, if no, go for next condition
if @finish[p] == 0 {
my $satisfied;
# Check if for all resources of current P need is less than work
LOOP: for ^R -> \j {
$satisfied = j;
last LOOP if @need[p;j] > @work[j]
}
if $satisfied == R - 1 { # If all needs of p were satisfied.
@work »+=« allot[p;^R]; # Free the resources
@safeSeq[$count] = p; # Add this process to safe sequence.
@finish[p] = 1; # Mark this p as finished
$count += 1;
$found = True }
}
}
# If we could not find a next process in safe sequence.
return False, "System is not in safe state." unless $found;
}
# If system is in safe state then safe sequence will be as below
return True, "Safe sequence is: " ~ @safeSeq
}
 
# Check system is in safe state or not
my ($safe-state,$status-message) = isSafe @avail, @maxm, @allot;
say "Safe state? $safe-state";
say "Message: $status-message";</lang>
{{out}}
<pre>Safe state? True
Message: Safe sequence is: 0 1 2</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence max_res = {6, 5, 7, 6},
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
curr = {{1, 2, 2, 1},
<span style="color: #004080;">sequence</span> <span style="color: #000000;">max_res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">},</span>
{1, 0, 3, 3},
<span style="color: #000000;">curr</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
{1, 2, 1, 0}},
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">},</span>
running = repeat(true,length(curr)),
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">}},</span>
max_claim = {{3, 3, 2, 2},
<span style="color: #000000;">running</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curr</span><span style="color: #0000FF;">)),</span>
{1, 2, 3, 4},
<span style="color: #000000;">max_claim</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">},</span>
{1, 3, 5, 0}},
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">},</span>
alloc = repeat(0,length(max_res))
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">}},</span>
 
<span style="color: #000000;">alloc</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">max_res</span><span style="color: #0000FF;">))</span>
integer count = length(curr)
for i=1 to count do
<span style="color: #004080;">integer</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curr</span><span style="color: #0000FF;">)</span>
alloc = sq_add(alloc,curr[i])
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">count</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">alloc</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">alloc</span><span style="color: #0000FF;">,</span><span style="color: #000000;">curr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
sequence avl = sq_sub(max_res,alloc)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #004080;">sequence</span> <span style="color: #000000;">avl</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">max_res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">alloc</span><span style="color: #0000FF;">)</span>
printf(1,"Available system resources: ") ?max_res
printf(1,"Process allocated: ") ?curr
printf(1,"Maximum resources: ") ?max_claim
printf(1,"Allocated resources: ") ?alloc
printf(1,"Available resources: ") ?avl
 
while count!=0 do
bool safe = false
for i=1 to length(curr) do
if running[i] then
bool execute = true
for j=1 to length(max_res) do
if max_claim[i][j]-curr[i][j] > avl[j] then
execute = false
exit
end if
end for
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Available system resources: %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">max_res</span><span style="color: #0000FF;">})</span>
if execute then
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Process allocated: %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">curr</span><span style="color: #0000FF;">})</span>
printf(1,"Process%d is executing. ", i)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Maximum resources: %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">max_claim</span><span style="color: #0000FF;">})</span>
running[i] = false
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Allocated resources: %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">alloc</span><span style="color: #0000FF;">})</span>
count -= 1
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Available resources: %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">avl</span><span style="color: #0000FF;">})</span>
safe = true
for j=1 to length(max_res) do
avl[j] += curr[i][j]
end for
exit
end if
end if
end for
<span style="color: #008080;">while</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
if not safe then
<span style="color: #004080;">bool</span> <span style="color: #000000;">safe</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
printf(1,"The processes are in an unsafe state.\n");
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curr</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
exit
<span style="color: #008080;">if</span> <span style="color: #000000;">running</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
end if
<span style="color: #004080;">bool</span> <span style="color: #000000;">execute</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span>
printf(1, "Safe state. Available resources: ") ?avl
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">max_res</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end while</lang>
<span style="color: #008080;">if</span> <span style="color: #000000;">max_claim</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">curr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">></span> <span style="color: #000000;">avl</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">execute</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">execute</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Process%d is executing. "</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">running</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
<span style="color: #000000;">count</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">safe</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">max_res</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">avl</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">curr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">safe</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The processes are in an unsafe state.\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Safe state. Available resources: %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">avl</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,092 ⟶ 1,363:
Available resources: {3,0,1,2}
The processes are in an unsafe state.
</pre>
 
=={{header|Python}}==
<syntaxhighlight lang="python">
def main():
resources = int(input("Number of resources: "))
processes = int(input("Number of processes: "))
max_resources = [int(i) for i in input("Maximum resources: ").split()]
 
print("\n-- resources allocated for each process --")
currently_allocated = [[int(i) for i in input(f"process {j + 1}: ").split()] for j in range(processes)]
 
print("\n--- maximum resources for each process ---")
max_need = [[int(i) for i in input(f"process {j + 1}: ").split()] for j in range(processes)]
 
allocated = [0] * resources
for i in range(processes):
for j in range(resources):
allocated[j] += currently_allocated[i][j]
print(f"\nTotal resources allocated: {allocated}")
 
available = [max_resources[i] - allocated[i] for i in range(resources)]
print(f"Total resources available: {available}\n")
 
running = [True] * processes
count = processes
while count != 0:
safe = False
for i in range(processes):
if running[i]:
executing = True
for j in range(resources):
if max_need[i][j] - currently_allocated[i][j] > available[j]:
executing = False
break
if executing:
print(f"process {i + 1} running")
running[i] = False
count -= 1
safe = True
for j in range(resources):
available[j] += currently_allocated[i][j]
break
if not safe:
print("The process is in an unsafe state.")
break
 
print(f"The process is in a safe state.\nAvailable resources: {available}\n\n")
 
 
if __name__ == '__main__':
main()
</syntaxhighlight>
{{out}}
<pre>
Number of resources: 4
Number of processes: 3
Maximum resources: 6 5 7 6
 
-- resources allocated for each process --
process 1: 1 2 2 1
process 2: 1 0 3 3
process 3: 1 2 1 0
 
--- maximum resources for each process ---
process 1: 3 3 2 2
process 2: 1 2 3 4
process 3: 1 3 5 0
 
Total resources allocated: [3, 4, 6, 4]
Total resources available: [3, 1, 1, 2]
 
process 1 running
The process is in a safe state.
Available resources: [4, 3, 3, 3]
 
process 2 running
The process is in a safe state.
Available resources: [5, 3, 6, 6]
 
process 3 running
The process is in a safe state.
Available resources: [6, 5, 7, 6]
</pre>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket/base
(require racket/block racket/pretty racket/port racket/vector)
 
Line 1,180 ⟶ 1,534:
 
EOS
(λ () (call-with-values bankers-input bankers-algorithm))))</langsyntaxhighlight>
 
{{out}}
Line 1,226 ⟶ 1,580:
 
Available vector: '#(8 5 9 7)</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
Based on the Python3 solution by Shubham Singh found
[https://www.geeksforgeeks.org/program-bankers-algorithm-set-1-safety-algorithm/ here]
<syntaxhighlight lang="raku" line>my @avail = <3 1 1 2>; # Available instances of resource
my @maxm = <3 3 2 2>, <1 2 3 4>, <1 3 5 0>; # Maximum resources that can be allocated to processes
my @allot = <1 2 2 1>, <1 0 3 3>, <1 2 1 0>; # Resources allocated to processes
 
# Function to find the system is in safe state or not
sub isSafe(\work is copy, \maxm, \allot) {
my \P = allot.elems; # Number of processes
my \Pool = (^P).SetHash; # Process pool
my \R = work.elems; # Number of resources
my \need = maxm »-« allot; # the need matrix
my @safe-sequence;
 
# While all processes are not finished or system is not in safe state
my $count = 0;
while $count < P {
my $found = False;
for Pool.keys -> \p {
if all need[p] »≤« work { # now process can be finished
work »+=« allot[p;^R]; # Free the resources
say 'available resources: ' ~ work;
@safe-sequence.push: p; # Add this process to safe sequence
Pool{p}--; # Remove this process from Pool
$count += 1;
$found = True
}
}
# If we could not find a next process in safe sequence
return False, "System is not in safe state." unless $found;
}
# If system is in safe state then safe sequence will be as below
return True, "Safe sequence is: " ~ @safe-sequence
}
 
# Check if system is in a safe state
my ($safe-state,$status-message) = isSafe @avail, @maxm, @allot;
say "Safe state? $safe-state";
say "Message: $status-message";</syntaxhighlight>
{{out}}
<pre>available resources: 4 3 3 3
available resources: 5 3 6 6
available resources: 6 5 7 6
Safe state? True
Message: Safe sequence is: 0 1 2</pre>
 
=={{header|Rust}}==
Line 1,231 ⟶ 1,633:
Adapted from the C language version. It crashes for invalid input.
 
<langsyntaxhighlight lang="rust">
fn read_numbers<T>() -> Vec<T>
where T: std::str::FromStr {
Line 1,350 ⟶ 1,752:
println!();
}
}</langsyntaxhighlight>
 
{{out|Input and Output}}
Line 1,399 ⟶ 1,801:
The process is in safe state.
The available vector is: 8 5 9 7
</pre>
 
=={{header|Scala}}==
{{trans|Python}}
<syntaxhighlight lang="Scala">
import scala.io.StdIn.readLine
 
object BankersAlgorithm {
def main(args: Array[String]): Unit = {
println("Number of resources: ")
val resources = readLine().toInt
 
println("Number of processes: ")
val processes = readLine().toInt
 
println("Maximum resources: ")
val maxResources = readLine().split(" ").map(_.toInt)
 
println("\n-- resources allocated for each process --")
val currentlyAllocated = Array.ofDim[Int](processes, resources)
for (i <- 0 until processes) {
println(s"process ${i + 1}: ")
currentlyAllocated(i) = readLine().split(" ").map(_.toInt)
}
 
println("\n--- maximum resources for each process ---")
val maxNeed = Array.ofDim[Int](processes, resources)
for (i <- 0 until processes) {
println(s"process ${i + 1}: ")
maxNeed(i) = readLine().split(" ").map(_.toInt)
}
 
val allocated = Array.fill(resources)(0)
for (i <- 0 until processes) {
for (j <- 0 until resources) {
allocated(j) += currentlyAllocated(i)(j)
}
}
println(s"\nTotal resources allocated: ${allocated.mkString(", ")}")
 
val available = maxResources.zip(allocated).map { case (max, alloc) => max - alloc }
println(s"Total resources available: ${available.mkString(", ")}\n")
 
var running = Array.fill(processes)(true)
var count = processes
 
while (count != 0) {
var safe = false
for (i <- 0 until processes if running(i)) {
var executing = true
for (j <- 0 until resources) {
if (maxNeed(i)(j) - currentlyAllocated(i)(j) > available(j)) {
executing = false
}
}
if (executing) {
println(s"process ${i + 1} is running")
running(i) = false
count -= 1
safe = true
for (j <- 0 until resources) {
available(j) += currentlyAllocated(i)(j)
}
}
}
 
if (!safe) {
println("The processes are in an unsafe state.")
return
}
 
println(s"The processes are in a safe state.\nAvailable resources: ${available.mkString(", ")}\n")
}
}
}
</syntaxhighlight>
 
'''input'''
 
<pre>
4
3
6 5 7 6
1 2 2 1
1 0 3 3
1 2 1 0
3 3 2 2
1 2 3 4
1 3 5 0
</pre>
{{out}}
<pre>
Number of resources: 4
Number of processes: 3
Maximum resources: 6 5 7 6
 
-- resources allocated for each process --
process 1: 1 2 2 1
process 2: 1 0 3 3
process 3: 1 2 1 0
 
--- maximum resources for each process ---
process 1: 3 3 2 2
process 2: 1 2 3 4
process 3: 1 3 5 0
 
Total resources allocated: 3, 4, 6, 4
Total resources available: 3, 1, 1, 2
 
process 1 is running
process 2 is running
process 3 is running
The processes are in a safe state.
Available resources: 6, 5, 7, 6
 
 
</pre>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">import Foundation
 
print("Enter the number of resources: ", terminator: "")
Line 1,506 ⟶ 2,024:
 
print("The available vector is: \(available)")
}</langsyntaxhighlight>
 
{{out|Input and Output}}
Line 1,545 ⟶ 2,063:
The process is in safe state.
The available vector is: [8, 5, 9, 7]</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="wren">import "io" for Stdin, Stdout
 
System.write("Enter the number of resources: ")
Stdout.flush()
var r = Num.fromString(Stdin.readLine())
 
System.write("\nEnter the number of processes: ")
Stdout.flush()
var p = Num.fromString(Stdin.readLine())
 
System.write("\nEnter Claim Vector: ")
Stdout.flush()
var maxRes = Stdin.readLine().split(" ").map { |s| Num.fromString(s) }.toList
 
System.print("\nEnter Allocated Resource Table:")
var curr = List.filled(p, null)
for (i in 0...p) {
System.write("Row %(i + 1): ")
Stdout.flush()
curr[i] = Stdin.readLine().split(" ").map { |s| Num.fromString(s) }.toList
}
 
System.print("\nEnter Maximum Claim Table: ")
var maxClaim = List.filled(p, null)
for (i in 0...p) {
System.write("Row %(i + 1): ")
Stdout.flush()
maxClaim[i] = Stdin.readLine().split(" ").map { |s| Num.fromString(s) }.toList
}
 
var alloc = List.filled(r, 0)
for (i in 0...p) {
for (j in 0...r) alloc[j] = alloc[j] + curr[i][j]
}
System.print("\nAllocated Resources: %(alloc.join(" "))")
 
var avl = List.filled(r, 0)
for (i in 0...r) avl[i] = maxRes[i] - alloc[i]
System.print("\nAvailable Resources: %(avl.join(" "))")
 
var running = List.filled(p, true)
var count = p
while (count != 0) {
var safe = false
for (i in 0...p) {
if (running[i]) {
var exec = true
for (j in 0...r) {
if (maxClaim[i][j] - curr[i][j] > avl[j]) {
exec = false
break
}
}
 
if (exec) {
System.print("\nProcess %(i + 1) is executing.")
running[i] = false
count = count - 1
safe = true
for (j in 0...r) avl[j] = avl[j] + curr[i][j]
break
}
}
}
 
if (!safe) {
System.print("\nThe processes are in an unsafe state.")
break
}
 
System.write("\nThe process is in a safe state.")
System.print("\nAvailable Vector: %(avl.join(" "))")
}</syntaxhighlight>
 
{{out}}
Sample input/output:
<pre>
Enter the number of resources: 4
 
Enter the number of processes: 5
 
Enter Claim Vector: 8 5 9 7
 
Enter Allocated Resource Table:
Row 1: 2 0 1 1
Row 2: 0 1 2 1
Row 3: 4 0 0 3
Row 4: 0 2 1 0
Row 5: 1 0 3 0
 
Enter Maximum Claim Table:
Row 1: 3 2 1 4
Row 2: 0 2 5 2
Row 3: 5 1 0 5
Row 4: 1 5 3 0
Row 5: 3 0 3 3
 
Allocated Resources: 7 3 7 5
 
Available Resources: 1 2 2 2
 
Process 3 is executing.
 
The process is in a safe state.
Available Vector: 5 2 2 5
 
Process 1 is executing.
 
The process is in a safe state.
Available Vector: 7 2 3 6
 
Process 2 is executing.
 
The process is in a safe state.
Available Vector: 7 3 5 7
 
Process 4 is executing.
 
The process is in a safe state.
Available Vector: 7 5 6 7
 
Process 5 is executing.
 
The process is in a safe state.
Available Vector: 8 5 9 7
</pre>
 
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
{{todo|Python|Translate all Spanish texts to English}}
<syntaxhighlight lang="yabasic">
clear screen
input "Ingrese la cantidad de recursos: " r
input "Ingrese la cantidad de procesos: " p
 
print "\nIngrese los recursos m ximos: "
dim maxRes(r)
for i = 1 to r
input " " maxRes(i)
next i
 
print "\n-- recursos asignados para cada proceso --"
dim curr(p, r)
for i = 1 to p
print "proceso ", i, ":"
for j = 1 to r
input " " curr(i, j)
next j
print
next i
 
print "\n--- recursos m ximos para cada proceso ---"
dim maxReclam(p, r)
for i = 1 to p
print "proceso ", i, ":"
for j = 1 to r
input " " maxReclam(i, j)
next j
print
next i
 
print "\nRecursos totales asignados : ";
dim recAsigad(r)
for i = 1 to p
for j = 1 to r
recAsigad(j) = recAsigad(j) + curr(i, j)
next j
next i
for i = 1 to r
print recAsigad(i), " ";
next i
 
dim recDispon(r)
print "\nRecursos totales disponibles: ";
for i = 1 to r
recDispon(i) = maxRes(i) - recAsigad(i)
print recDispon(i), " ";
next i
 
dim ejecutando(p)
for i = 1 to p
ejecutando(i) = True
next i
 
contar = p
while contar <> 0
seguro = False
for i = 1 to p
if ejecutando(i) then
ejecuta = True
for j = 1 to r
if (maxReclam(i,j) - curr(i,j) > recDispon(j)) then
ejecuta = False
break
end if
next j
if ejecuta then
print color("cya") "\n\nproceso ", i, " ejecut ndose."
ejecutando(i) = False
contar = contar - 1
seguro = True
for j = 0 to r
recDispon(j) = recDispon(j) + curr(i,j)
next j
break
end if
end if
next i
if not seguro then
print color("red") "\nLos procesos est n en un estado inseguro."
break
end if
print color("gre") "El proceso est  en un estado seguro."
print color("whi")"Recursos disponibles: ",
for i = 1 to r
print recDispon(i), " ";
next i
wend
print
end
</syntaxhighlight>
 
 
{{omit from|Blast}}
Line 1,550 ⟶ 2,296:
{{omit from|GUISS}}
{{omit from|Openscad}}
 
{{omit from|TPP}}
337

edits