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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

294 Tasks<br />

20.2.1 Putt<strong>in</strong>g it all together<br />

Us<strong>in</strong>g the new def<strong>in</strong>ition of the task type <strong>in</strong> the package Pack_factorial the follow<strong>in</strong>g code can now be<br />

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

20.3 Mutual exclusion and critical sections<br />

In many cases of real time work<strong>in</strong>g, sections of code must not be executed concurrently. The classic example is<br />

the add<strong>in</strong>g or remov<strong>in</strong>g of data <strong>in</strong> a shared buffer. For example, to perform a copy operation between two separate<br />

devices a shared buffer can be used to even out the differences <strong>in</strong> response-time. This can be illustrated<br />

diagrammatically as shown <strong>in</strong> Figure 20.3.<br />

Disk<br />

Reader<br />

task<br />

Writer<br />

task<br />

Disk<br />

Buffer<br />

Figure 20.3 Illustration of copy with a buffer to even out the differences <strong>in</strong> read and write rates.<br />

The problem is how to prevent both the read and write tasks access<strong>in</strong>g the buffer simultaneously, caus<strong>in</strong>g the<br />

consequential corruption of <strong>in</strong>dices and data. The solution is to have the buffer as an <strong>in</strong>stance of a protected type.<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!