Reputation: 195
I'm writing my first school project in Ada that is composed of tasks. I need to initialize an array once. Where in the program should I do it to make sure it runs only once? Does Ada use anything similar to a constructor? An array I need to initialize:
type Book is record
Quantity: Integer;
Price: Float;
end record;
type ArrayOfBooks is array (0 .. 5) of Book;
MyBooks: ArrayOfBooks;
Any help will be very appreciated.
Upvotes: 1
Views: 6584
Reputation: 31689
I'm not clear on what kind of initialization you need. I'm going to go over several possibilities; hopefully one of those suits your needs.
(1) You can include an initial expression in the declaration of the array:
MyBooks : ArrayOfBooks := (others => (Quantity => 0, Price => 0.0));
This initializes every element of MyBooks
to a record whose fields are 0
and 0.0
respectively. This initialization will be performed only once (assuming the main procedure executes only once). When the main procedure is executed, it first elaborates all the declarations in the declarative part of the procedure; elaborating the declaration of MyBooks
includes assigning the initial expression to it.
(2) If a simple initial expression isn't good enough and you need some code to do the initialization, you could write a function that returns an ArrayOfBooks
and use a function call as your initial expression. Alternatively, you could put your task declarations in a nested block, so that you can make sure you execute the initialization code before your tasks start up:
procedure Main is
...
MyBooks : ArrayOfBooks;
begin
... code to open a file, for example
for I in MyBooks'range loop
LoadInformationForOneBook (MyFile, MyBooks(I));
end loop;
declare
... Now declare your tasks. At this point, you can be sure
... that MyBooks has been initialized.
... The tasks will start up at this point.
begin
...
end;
end Main;
This will also ensure that the initialization is called only once.
(3) If you really need one of the tasks to initialize MyBooks
, and you want to arrange things so that the first task that gets to it initializes the array, you could do this by setting up a flag to tell you whether the array has been initialized. To do this correctly, so that you don't have a problem when two tasks reach that point at approximately the same time, you should set up a protected object. Since this is probably more than you need, I won't go into details unless you need them.
Upvotes: 5