1
votes

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.

e.g. 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?

1
That code is a long way from compiling. In procedure1, B is declared as Integer but you then assign an access value to it (new Integer). And in the other two subprograms, B appears to be a record type. And the reserved word body can’t appear in a package spec. - Simon Wright
1> This is not valid Ada code. 2> Did you mean a protected type as in concurrency ? if so read here : en.wikipedia.org/wiki/… - NWS

1 Answers

7
votes

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.