Ada Medium · Lesson 1 · On the house

Tasks

Concurrent units with task types, activation, termination, and waiting for completion. Lesson 1 is free — on the house.

Lessons · Ada Medium · Lesson 1 of 10 · On the house

Tasks

Concurrent units with task types, activation, termination, and waiting for completion.

Illustration for Ada
Lesson 1 is on the house.

A task runs concurrently with its parent. Declare a task type with a body: task type Worker (Id : Natural);.

Tasks declared in a block start when the block's begin is reached and the block won't exit until they all finish, so no explicit join is needed.

Discriminants pass startup data to each task instance.

delay 0.1; suspends a task for a duration; delay until T; for absolute times.

Output from several tasks interleaves unpredictably; collect results and print in a fixed order when determinism matters.

task types

with Ada.Text_IO; use Ada.Text_IO;

procedure Tasks_Demo is
   Results : array (1 .. 3) of Natural := (others => 0);

   task type Worker (Id : Positive);
   task body Worker is
      Sum : Natural := 0;
   begin
      for I in 1 .. Id * 1000 loop
         Sum := Sum + I mod 7;
      end loop;
      Results (Id) := Sum;
   end Worker;
begin
   declare
      W1 : Worker (1);
      W2 : Worker (2);
      W3 : Worker (3);
   begin
      null;   -- the block waits here for W1..W3 to finish
   end;
   for R of Results loop
      Put (R'Image);
   end loop;
   New_Line;
end Tasks_Demo;
Match this when you type.

Quiz

When do tasks declared in a block start?

Quiz

What does a block do when its local tasks are still running?

Quiz

How do you pass startup data to a task?

Quiz

Which statement waits until an absolute time?

Check

Match the still for: Tasks.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.