Banker's algorithm: Difference between revisions
Content added Content deleted
SqrtNegInf (talk | contribs) m (→{{header|Perl 6}}: replace loop/last, further tidying) |
SqrtNegInf (talk | contribs) m (→{{header|Perl}}: tidying) |
||
Line 901: | Line 901: | ||
use warnings; |
use warnings; |
||
use feature 'say'; |
use feature 'say'; |
||
⚫ | |||
my $R = 4; # Number of resources |
|||
my @avail = (3, 1, 1, 2); # Available instances of resource |
my @avail = (3, 1, 1, 2); # Available instances of resource |
||
Line 911: | Line 908: | ||
# Function to find the system is in safe state or not |
# Function to find the system is in safe state or not |
||
sub isSafe { |
sub isSafe { |
||
my($ |
my($work, $maxm, $allot) = @_; |
||
⚫ | |||
my $satisfied; |
|||
my @ |
my $R = @$work; # Number of resources |
||
my @unfinished = (1) x $P; # Mark all processes as unfinished |
|||
my(@safeSeq,@need); |
|||
⚫ | |||
for my $i (0..$P-1) { # Calculating need of each process: |
|||
⚫ | |||
$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 |
# While all processes are not finished or system is not in safe state |
||
my $count = 0; |
my $count = 0; |
||
while ($count < $P) { |
while ($count < $P) { |
||
# can be satisfied with current @work resources. |
|||
my $found = 0; |
my $found = 0; |
||
for my $p (0..$P-1) { |
for my $p (0..$P-1) { |
||
# |
# While a process is not finished |
||
if ($ |
if ($unfinished[$p]) { |
||
# Check if for all resources of current P need is less than work |
# Check if for all resources of current P need is less than work |
||
my $satisfied; |
my $satisfied; |
||
LOOP: |
LOOP: for my $j (0..$R-1) { |
||
for my $j (0..$R-1) { |
|||
$satisfied = $j; |
$satisfied = $j; |
||
last LOOP if $need[$p][$j] > $work[$j] |
last LOOP if $need[$p][$j] > $$work[$j] |
||
} |
} |
||
# If all needs of p were satisfied |
# If all needs of p were satisfied |
||
if ($satisfied == $R-1) { |
if ($satisfied == $R-1) { |
||
$work[$_] += |
$$work[$_] += $$allot[$p][$_] for 0..$R-1; # free the resources |
||
say 'available resources: ' . join ' ', @$work; |
|||
push @safeSeq, $p; # Add this process to safe sequence |
|||
$unfinished[$p] = 1; # Mark this process as finished |
|||
$count += 1; |
$count += 1; |
||
$found = 1 |
$found = 1 |
||
Line 960: | Line 955: | ||
say "Message: $status_message";</lang> |
say "Message: $status_message";</lang> |
||
{{out}} |
{{out}} |
||
<pre> |
<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> |
Message: Safe sequence is: 0 1 2</pre> |
||