Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 36 ยท Tasking and Concurrency

Tasks and Task Types

Learn how Ada builds concurrency into the language: task declarations, task types, discriminants, activation, termination and master scopes, with runnable C stand-ins.

Most languages bolt concurrency on through a library: threads, locks, executors. Ada puts it in the language. A task is a unit of concurrent execution declared with the same syntax as any other program unit, and the compiler and runtime know how to start it, wait for it and clean up after it. This is one of the reasons Ada is trusted for control systems that must run several activities at once.

A note on what runs here: the Ada compiler (GNAT) is not available on this site, so the Ada code in this chapter is read-only, and we only show output when we are certain of it. Next to each idea you get a small, runnable C stand-in that uses POSIX threads. The stand-ins show the same idea; they are not Ada and they are labelled as such.

A single task

A task has a specification and a body, like a package. A task declared directly in a declarative part is started automatically.

ADA
with Ada.Text_IO; use Ada.Text_IO;

procedure Hello_Tasks is

   task Worker;                      --  specification

   task body Worker is
   begin
      Put_Line ("Worker: running");
   end Worker;

begin
   Put_Line ("Main: running");
end Hello_Tasks;

The task Worker is activated just before the first statement of the begin part of Hello_Tasks. From then on the main subprogram and Worker run concurrently, so the two lines can appear in either order. The main subprogram does not simply end when its last statement is done: a procedure cannot return until every task declared inside it has finished. That rule is the heart of Ada's structured concurrency and is explained in the master scopes section below.

Task types

A single task Worker; is really an anonymous object of a task type. When you need several similar tasks, declare the type and then create objects of it, often with a discriminant to tell them apart.

ADA
task type Counter (Id : Positive; Limit : Natural);

task body Counter is
   Total : Natural := 0;
begin
   for I in 1 .. Limit loop
      Total := Total + I;
   end loop;
   Put_Line ("Task" & Id'Image & " sum =" & Total'Image);
end Counter;

A : Counter (Id => 1, Limit => 10);
B : Counter (Id => 2, Limit => 100);

Each object has its own local variables (Total above), so tasks of the same type do not interfere with one another unless they share something on purpose. You can also build arrays of tasks, allocate tasks with new, and store them inside records; the same activation and termination rules apply.

Life of an Ada task

Declared task or task type
Activated before main's begin
Running concurrent with others
Completed end of body reached

A scope only exits when its tasks are terminated.

1 / 2

Activation, completion and masters

Every task depends on a master: the block, subprogram or library package whose declarative part contains it. Three steps define its life:

  1. Activation. Tasks declared in a declarative part start when elaboration of that part finishes, before the first statement.
  2. Completion. A task completes when it reaches the end of its body (or an unhandled exception ends it).
  3. Termination. A master may only leave once all the tasks that depend on it have terminated.

The consequence is that the stack frame holding a task's data can never disappear while the task still uses it. A language with free-floating threads has to rely on the programmer for that guarantee, and sometimes gets it wrong.

ADA
procedure Scoped is
begin
   declare
      task Helper;
      task body Helper is
      begin
         delay 1.0;
      end Helper;
   begin
      Put_Line ("block body done");
   end;                    --  waits here until Helper has terminated
   Put_Line ("after block");
end Scoped;

The delay 1.0 suspends Helper for one second. Even though the block body finishes at once, the block cannot exit until Helper terminates, so "after block" is printed only after the second has passed.

Stand-in: tasks as threads (C, runnable)

The C program below creates three worker "tasks" with POSIX threads, gives each one an id and a limit (like the discriminants of Counter), and the main thread joins them before finishing, which is what an Ada master does implicitly. Output is collected in per-thread slots and printed after the joins, so it is the same on every run.

C C stand-in: task type with discriminants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

In Ada you never write the pthread_join loop: leaving the scope is the join.

Stand-in: why the master must wait

This second stand-in shows what the rule prevents. The worker uses data that lives in main; because main joins before returning, that data is still valid when the worker reads it.

C C stand-in: data outlives the worker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Assuming an order. Output from two tasks interleaves unpredictably. Use rendezvous or protected objects (next lessons) when order matters.
  • Sharing variables freely. Two tasks writing one variable without protection is a data race. Ada gives you protected objects so you do not need raw locks.
  • Forgetting that the main program waits. A program whose task has an infinite loop never exits unless the task can terminate; see select, delay and termination.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When is a task declared in a procedure's declarative part activated?

    Tasks are activated automatically once the declarative part has been elaborated, before the first statement of the body.
  2. 2. What does it mean that a procedure is the master of tasks declared inside it?

    A master waits for its dependent tasks, so data in its frame can never disappear under a running task.
  3. 3. What is the difference between a task and a task type?

    A single task is an object of an anonymous type; a task type is a template for any number of task objects.
  4. 4. Why do the C examples use pthread_join?

    In Ada, leaving the master scope waits for the tasks; in C you must join explicitly.

Summary

  • A task is a concurrent unit with a specification and a body; a task type is a template for many.
  • Tasks activate automatically before the first statement of their master.
  • A master cannot exit until its dependent tasks have terminated, which keeps data alive.
  • Discriminants parameterize each task object.
  • The C stand-ins use POSIX threads to show the same ideas; they are not Ada.

Next: Rendezvous and Entries