Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- repair this program according to the lab sheet.
- with Ada.Text_IO; use Ada.Text_IO;
- procedure Counter_Test_Synchronized is
- -- Lamport's bakery Algorithm
- -- References :
- -- https://en.wikipedia.org/wiki/Lamport%27s_bakery_algorithm
- -- https://www.geeksforgeeks.org/operating-system-bakery-algorithm/
- subtype Task_Index is Positive range 1 .. 4;
- type Ticket_Array is array (Task_Index) of Integer;
- Choosing : array (Task_Index) of Boolean := (Task_Index'First .. Task_Index'Last => False);
- Number : Ticket_Array := (Task_Index'First .. Task_Index'Last => 0);
- function Get_Max (Array_X : Ticket_Array) return Integer is
- max : Integer := Integer'First;
- begin
- for I in Array_X'Range loop
- if max < Array_X (I) then
- max := Array_X (I);
- end if;
- end loop;
- return max;
- end Get_Max;
- procedure Lock (Task_ID : Task_Index) is
- begin
- Choosing (Task_ID) := True; -- indicate intent to enter critical section
- Number (Task_ID) := 1 + Get_Max (Number); -- gives the highest ticket number
- Choosing (Task_ID) := False; -- to indicate that the ticket number has been obtained
- for I in Task_Index loop
- while Choosing (I) loop
- null; -- wait until thread I receives its ticket
- end loop;
- while
- Number (I) /= 0 and then
- (Number (I) < Number (Task_ID) or else
- (Number (I) = Number (Task_ID) and then I < Task_ID))
- loop
- -- wait until all thread with smaller ticket or with the same ticket
- -- number but with higher priority (i.e. smaller task ID) finish their
- -- work
- null;
- end loop;
- end loop;
- end Lock;
- procedure Unlock (Task_ID : Task_Index) is
- begin
- Number (Task_ID) := 0;
- end Unlock;
- -- End of bakery algorithm
- -- Shared variable
- Sum : Natural := 50;
- --
- task type Counter (Id : Positive; Goal : Natural);
- task body Counter is
- begin
- -- start critical section
- Lock (Id);
- while Sum /= Goal loop
- Sum := (if Sum > Goal then Sum - 1 else Sum + 1);
- Put (Natural'Image (Sum));
- end loop;
- New_Line;
- Put_Line ("Counter task" & Positive'Image (Id) & " terminates with sum being:" & Natural'Image (Sum));
- Unlock (Id);
- -- end critical section
- end Counter;
- -- Declare tasks
- Counter_1 : Counter (1, 30);
- Counter_2 : Counter (2, 40);
- Counter_3 : Counter (3, 60);
- Counter_4 : Counter (4, 70);
- begin
- New_Line;
- Put_Line ("Counter_Test terminates with sum being:" & Natural'Image (Sum));
- end Counter_Test_Synchronized;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement