4

C の pthread_barrier_wait と同様の機能を持つバリアを Ada に実装しようとしています。Ada 2012 には Ada.Synchronous_Barriers がありますが、私のシステムでは利用できません (debian lenny の gnu-gnat)。

より具体的には、Ada 2012 を使用せずに、待機中のすべてのタスクを同時にバリアから解放し、理想的には、これらのタスクの 1 つに何か特別なことをさせるにはどうすればよいですか? 以下は、非常に最適ではない実装です。より良いアプローチは何ですか?

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure foobar is
   protected Synchronizer is
      entry Ready_For_Action; -- prepares for tasks to wait at barrier
      entry Wait_For_Release; -- barrier
      -- do work here
      entry Done;             -- signals that all tasks are done
      entry Wait_For_Others;  -- prepares for prepare to wait at barrier
   private
      ready, active: Natural := 0;  
      -- two state variables seem to be needed as entry conditions can't
      --    safely modify the condition variable as that influences wait
      --    state in other tasks
   end Synchronizer;

   NUM_OBJECTS: constant := 3;

   protected body Synchronizer is
      entry Ready_For_Action when active = 0 is
      begin
         ready := ready + 1;
      end Ready_For_Action;
      --
      entry Wait_For_Release when ready = NUM_OBJECTS is
      begin
         active := active + 1;
      end Wait_For_Release;
      --
      entry Done when active = NUM_OBJECTS is
      begin
         ready := ready - 1;
      end Done;
      --
      entry Wait_For_Others when ready = 0 is
      begin
         active := active - 1;
      end wait_for_others;
      --
   end Synchronizer;

   task type Foo(N: Natural);

   task body Foo is
      id: Natural := N;
   begin
      for iter in 1..3 loop
         Synchronizer.Ready_For_Action;
         Synchronizer.Wait_For_Release;
         -- task N doing something special
         if id = 1 then new_line; end if;
         -- do stuff here
         delay 0.1;
         put(id); new_line;
         -- re-sync
         Synchronizer.Done;
         Synchronizer.Wait_For_Others;
      end loop;
   end Foo;
   Task1: Foo(1);
   Task2: Foo(2);
   Task3: Foo(3);
begin
   Null;
end foobar;

プログラム出力:

$ ./foobar 
  3
  1
  2

  3
  1
  2

  3
  2
  1
4

2 に答える 2

2

エントリの 'count 属性が役立つかもしれません - これはあなたが探しているものですか? タスク ID を使用して別のことを行うのは賢明なようです (または、十分に異なる場合は、新しいタスク タイプを作成することもできます)。

No_Of_Tasks : Natural := 3;
   --
protected Barrier is
   entry Continue;
private
   Released : Boolean := False;
end Barrier
   --
protected body Barrier is 
   entry Continue when (Released or else Continue'count = No_Of_Tasks)
      Released := Continue'count > 0; -- the last task locks the barrier again
   end Continue                       
end Barrier                           
于 2015-12-11T05:36:10.867 に答える