Ada 中的信号量 [英] Semaphores in Ada
问题描述
我收到了以下代码并要求我实现一个信号量.
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;
该任务需要一个 Semaphores
包和一个包 Id_Dispenser
.我对 Ada 很陌生,但是包是什么意思?这意味着规范和正文还是只有一个,我将如何实施?
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?
推荐答案
包是什么意思?
As suggested here, an Ada package provides for modular programming to support encapsulation.
该任务需要一个 Semaphores
包.
The task requires a
Semaphores
package.
为此,Ada 提供了受保护的类型封装并提供对该类型对象的私有数据的同步访问,而无需引入额外的任务."可以在此处找到其他讨论和示例.
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.
在用餐哲学家问题的背景下,这个完整的example 值得一读;它包含在 share/examples/gnat/simple_project
GNAT 社区版中>.特别是,package Chop
导出protected type Stick
;Stick
的每个实例都有一个 entry Pick_Up
和 procedure Put_Down
.package Room
然后可以保存一系列可供用餐者使用的餐具,对应于您片段中的 Forks
.
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;
这篇关于Ada 中的信号量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!