18.10.2014 Views

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

304 Tasks<br />

20.8.2 As part of a program unit<br />

package Pack_Factorial is<br />

task type Task_Factorial(F:Positive) is --Specification<br />

entry F<strong>in</strong>ish( Result:out Positive ); --Rendezvous<br />

end Task_Factorial;<br />

end Pack_Factorial;<br />

--[pack_factorial.adb] Implementation<br />

package body Pack_Factorial is<br />

task body Task_Factorial is --Implementation<br />

Answer : Positive := 1;<br />

beg<strong>in</strong><br />

for I <strong>in</strong> 2 .. F loop<br />

--Calculate<br />

Answer := Answer * I;<br />

end loop;<br />

accept F<strong>in</strong>ish( Result:out Positive ) do --Return answer<br />

Result := Answer;<br />

end F<strong>in</strong>ish;<br />

end Task_Factorial;<br />

end Pack_Factorial;<br />

with <strong>Ada</strong>.Text_Io, <strong>Ada</strong>.Integer_Text_Io, Pack_Factorial;<br />

use <strong>Ada</strong>.Text_Io, <strong>Ada</strong>.Integer_Text_Io, Pack_Factorial;<br />

procedure Ma<strong>in</strong> is<br />

Num : Positive;<br />

beg<strong>in</strong><br />

Num := 7;<br />

declare<br />

Factorial: Positive;<br />

Thread_1 : Task_Factorial(Num);<br />

beg<strong>in</strong><br />

--Do some other work as well<br />

Put("Factorial "); Put(Num); Put(" is ");<br />

Thread_1.F<strong>in</strong>ish( Factorial );<br />

Put( Factorial ); New_L<strong>in</strong>e;<br />

end;<br />

--Answer<br />

--Task is<br />

--Obta<strong>in</strong> result<br />

end Ma<strong>in</strong>;<br />

Note:<br />

The task will come <strong>in</strong>to existence as soon as the program unit is executed.<br />

20.9 Self-assessment<br />

• What is a thread or task <strong>in</strong> a programm<strong>in</strong>g language?<br />

• What <strong>Ada</strong> construct can be used to implement a thread or task?<br />

• How is <strong>in</strong>formation passed between two threads? Expla<strong>in</strong> why a special construct is required for this<br />

activity.<br />

• What is the difference between a task type and a normal type?<br />

• What is the difference between execution of a procedure and execution of a function <strong>in</strong> a protected<br />

type?<br />

• What happens when a task type is elaborated?<br />

© M A Smith - May not be reproduced without permission

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!