Reputation: 139
I have been given the following code and asked to implement a semaphore.
with Ada.Text_IO; use Ada.Text_IO;
with Id_Dispenser;
with Semaphores; use Semaphores;
procedure Philos is
No_of_Philos : constant Positive := 5;
Meditation : constant Duration := 0.0;
type Table_Ix is mod No_of_Philos;
Forks : array (Table_Ix) of Binary_Semaphore (Initially_Available => True);
package Index_Dispenser is new Id_Dispenser (Element => Table_Ix);
use Index_Dispenser;
task type Philo;
task body Philo is
Philo_Nr : Table_Ix;
begin
Dispenser.Draw_Id (Id => Philo_Nr);
Put_Line (“Philosopher” & Table_Ix’Image (Philo_Nr) & “ looks for forks.”);
Forks (Philo_Nr).Wait; delay Meditation; Forks (Philo_Nr + 1).Wait;
Put_Line (“Philosopher” & Table_Ix’Image (Philo_Nr) & “ eats.”);
Forks (Philo_Nr).Signal; Forks (Philo_Nr + 1).Signal;
Put_Line (“Philosopher” & Table_Ix’Image (Philo_Nr) & “ dropped forks.”);
end Philo;
Table : array (Table_Ix) of Philo; pragma Unreferenced (Table);
begin
null;
end Philos;
The task requires a Semaphores
package and a package Id_Dispenser
. I am very new to Ada, but what is meant by a package? Does this mean both specification and body or just one, and how shall I go about implementing this?
Upvotes: 1
Views: 685
Reputation: 205865
What is meant by a package?
As suggested here, an Ada package provides for modular programming to support encapsulation.
The task requires a
Semaphores
package.
To this end, Ada offers protected types "which encapsulate and provide synchronized access to the private data of objects of the type without the introduction of an additional task." Additional discussion and examples may be found here.
In the context of the dining philosophers problem, this complete example is worth reading; it is included in the GNAT community edition in share/examples/gnat/simple_project
. In particular, the package Chop
exports protected type Stick
; each instance of Stick
has an entry Pick_Up
and procedure Put_Down
. The package Room
can then hold an array of utensils available to the diners, corresponding to Forks
in your fragment.
Sticks : array (Table_Type) of Chop.Stick;
Upvotes: 2
Reputation: 25511
As to "what is a package", check out the Packages section in the Ada Wikibook.
All packages have a specification part. Most also have a body (and if the spec promises one, for example by declaring a subprogram, there must actually be one).
You can find discussion of implementing a semaphore in the Wikibook section on Tasking, including code for a Semaphore_Protected_Type
.
In your case, you need
package Semaphores is
protected type Binary_Semaphore (Initially_Available : Boolean) is
entry Wait;
procedure Signal;
private
Available : Boolean := Initially_Available;
end Binary_Semaphore;
...
end Semaphores;
Upvotes: 2