Banker's algorithm: Difference between revisions

Content added Content deleted
m (→‎{{header|Perl 6}}: replace loop/last, further tidying)
Line 901:
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 ⟶ 908:
# Function to find the system is in safe state or not
sub isSafe {
my($availwork, $maxm, $allot) = @_;
my $P = 3@$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) { # Need of instance = 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 960 ⟶ 955:
say "Message: $status_message";</lang>
{{out}}
<pre>Safeavailable state?resources: True4 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>