Using semaphores to call functions that are not thread safe and potentialy blocking


   protected Semaphore is
      entry Seize;
      entry Release;
   private
      Busy : Boolean := False;
   end Semaphore;

   protected body Semaphore is

      entry Seize when not Busy is
      begin
         Busy := True;
      end;

      entry Release when Busy is
      begin
         Busy := False;
      end;

   end Semaphore;

   function Gethostbyname (Name : in System.Address)
      return System.Address; -- pointer to hostent

   pragma Import(C, Gethostbyname);

   function Protected_Gethostbyname (Name : in System.Address)
      return System.Address is

      Result : System.Address;

   begin
      Semaphore.Seize;
      Result := Gethostbyname(Name);
      Semaphore.Release;
      return Result;
   exception
      when others =>
         Semaphore.Release;
         raise;
   end Protected_Gethostbyname;

it would be nice to put the call to gethostbyname inside a protected procedure (so that you need only one protected call instead of two), but this does not seem to be allowed as gethostbyname could be potentially blocking.


Contributed by: Mats Weber
Contributed on: November 29, 1998
License: Public Domain
Back
[Note from editor:] It has been pointed out by Jeff Email that on some platforms this example will not work for the function gethostbyname() since it is not reentrant do to an internal pointer to a static variable.