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.

Tasks 293<br />

Likewise, the task Task_Is_Prime <strong>in</strong> the package Pack_Is_A_Prime receives and delivers data to<br />

another thread of control.<br />

package body Pack_Is_A_Prime is<br />

task body Task_Is_Prime is --Implementation<br />

Prime : Positive;<br />

Answer: Boolean := True;<br />

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

accept Start( P:<strong>in</strong> Positive ) do --Factorial<br />

Prime := P;<br />

end Start;<br />

for I <strong>in</strong> 2 .. Prime-1 loop --Calculate<br />

if Prime rem I = 0 then<br />

Answer := False; exit;<br />

end if;<br />

end loop;<br />

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

Result := Answer;<br />

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

end Task_Is_Prime;<br />

end Pack_Is_A_Prime;<br />

20.2 Parameters to a task type<br />

In the previous example, the rendezvous Start is used to pass <strong>in</strong>itial values to the task. This can be done<br />

explicitly, when the task is created by us<strong>in</strong>g a discrim<strong>in</strong>ated task type. However, the discrim<strong>in</strong>ant must be a<br />

discrete type or access type. For example, the specification of the task Task_Factorial can be def<strong>in</strong>ed as<br />

follows:<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 />

Then an <strong>in</strong>stance of the task can be elaborated as follows:<br />

Thread_1 : Task_Factorial(7);<br />

--Task is<br />

The body of the task type is now:<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 />

Note:<br />

The discrim<strong>in</strong>ant to the task type is not specified <strong>in</strong> the body.<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!