Section 13.2 - Creating and Communicating with Tasks

Let's start by looking at an example of a trivial task. Let's create a type of task that waits for a "Start" request, prints a line of text for a number of times, and then terminates itself.

We'll wait a second between printing each line of text, which will help you see what it does. To make it more interesting, we'll include in the Start request the message to be printed and the number of times it's to print.

First, let's create a task type; the task type will be called Babbler, and its declaration could look like the following:

  with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;

  task type Babbler is
    entry Start(Message : String; Count : Natural);
  end Babbler;

Just like packages and subprograms, tasks have a declaration and a body. The task body could look like this:

  with Ustrings;   use Ustrings;

  task body Babbler is
    Babble : Unbounded_String;
    Maximum_Count : Natural;
  begin
    accept Start(Babble, Maximum_Count); -- Wait for Start message.
    for I in 1 .. Maximum_Count loop
      Put_Line(Babble);
      delay 1.0;       -- Wait for one second.
    end loop;
    -- We're done, exit task.
  end Babbler;

Here's a short procedure to demonstrate this task type; we'll call it the procedure Noise. Noise will create two tasks of the given task type and send them Start messages. Note how similar creating a task is to creating a variable from an ordinary type:

  with Babbler, Ada.Strings.Unbounded;
  use  Babbler, Ada.Strings.Unbounded;

  procedure Noise is
    Babble_1 : Babbler;  -- Create a task.
    Babble_2 : Babbler;  -- Create another task.
  begin
    -- At this point we have two active tasks, but both of them
    -- are waiting for a "Start" message. So, send them a Start.
    Babble_1.Start(To_Unbounded_String("Hi, I'm Babble_1"), 10);
    Babble_2.Start(To_Unbounded_String("And I'm Babble_2"), 6);
  end Noise;

A procedure that declares a task instance, like procedure Noise, is called a Master. A master must wait for all its tasks to terminate before it can terminate, so Noise will wait until Babble_1 and Babble_2 have exited before it exits.

When procedure Noise makes a ``call'' to Babble_1 and Babble_2's `Start' entry, it is performing what is called a rendezvous.


Quiz:


Should you see text from Babble_1 and Babble_2 interleaved on your display when you run Noise?
  1. Yes.
  2. No.

You may also:

PREVIOUS Go back to the previous section

NEXT     Skip to the next section

OUTLINE  Go up to the outline of lesson 13

David A. Wheeler (wheeler@ida.org)