taskada

How to Implement an Backround Task in Ada?


Is there an way To run an Ada Task in Backround ?

package body Main is

   task type Background is end Background;

   task body Background is
         
   begin
        
      loop
         
         delay 1.0;
         Do_Stuff;
         
      end loop;
         
   end Background;

   
   procedure Enable is
      
     B_TASK:Background;
   begin 
      
      --Please do not wait here..
      null;
      
   end Enable;
   

end Main;


Solution

  • Your question is a little vague (the meaning of "background" is unclear), but from the code example it seems you want a procedure Enable such that when it is called, a new "Background" task is started and Enable can return to its caller without waiting for the new task to terminate, leaving the new task running concurrently with the original task that called Enable.

    You can create such "background" tasks by creating them dynamically, using an access type and the "new" keyword:

    type Background_Ref is access Background;
    
    procedure Enable
    is
        B : Background_Ref := new Background;
        -- A new Background task is created and starts running
        -- concurrently with the present task.
    begin
        null;
        -- This does not wait for the new task to terminate.
    end Enable;
    

    Note that in this case the program itself will wait for all created background tasks to terminate, before the whole program terminates.