AdaPower Logged in as Guest
Ada Tools and Resources

Ada 95 Reference Manual
Ada Source Code Treasury
Bindings and Packages
Ada FAQ


Join >
Home >
Articles >
Getting Started >
Ada FAQ >
Source Treasury >
Books & Tutorials >
Packages for Reuse >
Latest Additions >
Ada Projects >
Press Releases >
Ada Audio / Video >
Home Pages >
Links >
Contact >
About >
Login >
Back
Tasking Hello World (James S. Rogers)

Ada provides all the expected features of a general purpose programming language. Ada also provides a programmer with an extensive set of tools for producing programs with concurrently executing modules. Ada calls concurrently executing modules "tasks".

The following program demonstrates some simple Ada tasking capablities by abusing the traditional "Hello World" program.

Each line of output in the following program is written by a separate task. The tasks are designed to take random amounts of time to finish their work. This causes the order of output to be different each time the program is run.

Three task objects are declared as M1, M2, M3. If the tasks did not run concurrently the output would always be in the expected order. The fact that the order of the output changes each time the program is run proves that the three tasks must be executing at the same time.

The Ada.Strings.Unbounded package is used inside each task to hold a variable length string with a maximum size of 72 characters, allowing you to force each task to produce a line full of output without causing formatting problems on the average screen.

A random number generator is used to cause each task to delay between 0.0 and 1.0 seconds. This random delay causes each task to take a different amount of time to complete. The task finishing first will write its output to the screen first.

-----------------------------------------------------------------------
-- Hello World program in Ada using tasking
-----------------------------------------------------------------------

with Ada.Text_Io;
with Ada.Strings.Bounded;
with Ada.Numerics.Float_Random;

procedure HelloTask is
   package Inner_Message is new
   Ada.Strings.Bounded.Generic_Bounded_Length(72);
   use Inner_Message;

   task type Messenger is
      entry Start(Message : in String);
   end Messenger;

  task body Messenger is
     use Ada.Numerics.Float_Random;
     Seed : Generator;
     Msg : Bounded_String;
  begin
     accept Start(Message : in String)
     do
        Msg := To_Bounded_String(Message);
     end Start;
     Reset(Seed);
     delay Duration(Random(Seed));
     Ada.Text_Io.Put_Line(To_String(Msg));
  end Messenger;

  M1 : Messenger;
  M2 : Messenger;
  M3 : Messenger;

begin

  M1.Start("Hello");
  M2.Start("From");
  M3.Start("Ada !");

end HelloTask;


(c) 1998-2004 All Rights Reserved David Botton