I've got a simple package in Ada with procedures and functions. I'd like to have all the functions and procedures in a protected type.
eg for a simple .adb file
package body Pack is
procedure procedure1 (B : in out Integer) is
begin
B := new Integer;
end procedure1;
procedure procedure2 (B: in out Integer) is
begin
B.Cont(B.First-1) := 1;
end procedure2;
function procedure3 (B : Integer) return Boolean is
begin
return B.First = B.Last;
end procedure3;
end pack;
and or a simple .ads
package body Pack is
procedure procedure1 (B : in out Integer);
procedure procedure2 (B: in out Integer);
function procedure3 (B : Integer) return Boolean;
end pack;
How would I go about it?
The thing about a protected type is that it protects something (against concurrent access). It's hard to see from your code what it is you want to protect.
If, say, you wanted to do a thread-safe increment, you might have a spec like
package Pack is
protected type T is
procedure Set (To : Integer);
procedure Increment (By : Integer);
function Get return Integer;
private
Value : Integer := 0;
end T;
end Pack;
(this is far from perfect; you'd like to be able to specify the initial Value
when you declare a T
, but that's starting to get complicated).
In this case, the thing to be protected is the Value
. You want to be sure that if two tasks call Increment
at the “same” time, one with By => 3
and one with By => 4
, the Value
ends up being incremented by 7.
The body could look like
package body Pack is
protected body T is
procedure Set (To : Integer) is
begin
Value := To;
end Set;
procedure Increment (By : Integer) is
begin
Value := Value + By;
end Increment;
function Get return Integer is
begin
return Value;
end Get;
end T;
end Pack;
Recommended reading: the Wikibooks section on protected types.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.