user3943076
user3943076

Reputation:

Can't handle exceptions in ada tasks

I have the following example:

with Ada.TEXT_IO;
use Ada.TEXT_IO;

procedure main is

  task Test is
    entry Call1;
    entry Call2;
  end Test;

  task body Test is
    Num : Integer := 5;
  begin
    loop
      select when Num < 5 =>
        accept Call1 do
          Put_Line("Call1 called!");
        end Call1;
      or when Num > 5 =>
        accept Call2 do
          Put_Line("Call2 called!");
        end Call2;
      or
        terminate;
      end select;
    end loop;
    exception when PROGRAM_ERROR => Put_Line("Nothing to call... :(");
  end Test;

begin
  Test.Call1;
end;

If I'm right, the task gets program_error when it can't call anything. When I run it, it stuck in an endless while loop. How can I solve the problem?

Upvotes: 0

Views: 533

Answers (1)

Simon Wright
Simon Wright

Reputation: 25511

I take it you’re trying to explore what happens when there are no open select alternatives as in ARM 9.7.1(21),

The exception Program_Error is raised if all alternatives are closed and there is no else part.

The thing is, terminate is a select alternative ((4), ibid) and can’t be closed, so not all alternatives are closed and Test is sitting at the terminate, prepared to die when the main program exits. But the main program is sitting at Test.Call1. Deadlock.

If you eliminate the or terminate, you get the Program_Error you were expecting; the task dies, and the main program gets Tasking_Error.

In an ideal world the compiler would catch the fact that neither accept can ever be open; presumably no one has felt deeply enough to implement the check (normally the problem would be much less obvious).

Upvotes: 2

Related Questions