SlideShare a Scribd company logo
Reliable and Concurrent Software
Reliable and Concurrent Software
Ada
Ada
PDEEC
2009/2010
1
Context
Context
 1973: the DoD (world largest software buyer), was concerned in finding a
programming language generally suitable for the department's
requirements.
◦ Data: at that time 450 different languages were used in the DoD
◦ Non fulfilled the requirements
 Approach: to develop a new language.
◦ International competition, 3 final candidates for development: Pascal, PL/I,Algol
68, Pascal (green language) won
 Ada was named after Augusta Ada Byron (1815-52), daughter of the poet
Lord Byron, and assistant of Charles Babbage
◦ Ada was the world’s first Programmer).
 Ada becomes ISO standard 8652 in 1987 and a revised version was
released in 95 (Ada 95). Further improvements were included in Ada 2005,
and Ada 2012 is next
2
Context
Context
 Goals
◦ Readability – professional programs are read much more often than they are written.
◦ Strong typing – More errors catch by the compiler.
◦ Programming in the large – mechanisms for encapsulation, separate compilation and
library management are necessary for the writing of portable and maintainable
programs of any size.
◦ Exception handling – Control unusual events.
◦ Data abstraction – extra portability and maintainability if the details of representation
of data are kept separate from the specification of the logical operations on data.
◦ Object oriented programming – reuse, polymorphism, inheritance.
◦ Tasking – parallel activities.
◦ Generic units – logic independent of the types.
◦ Interface – able to communicate with systems possibly written in other languages.
 We can do whatever we want – we just need to inform the compiler
we know what we are doing
3
Tasks
Tasks
 In Ada, parallel activities are
defined by means of tasks.
 A task is lexically described
by a form very similar to a
package.
 It consists of the interface
presented to other tasks
and a body describing the
dynamic behaviour of the
task.
4
procedure Shopping is
task Get_Salad;
task body Get_Salad is
begin
Buy_Salad;
end Get_Salad;
task Get_Wine;
task body Get_Wine is
begin
Buy_Wine;
end Get_Wine;
begin
Buy_Meat;
end Shopping;
Tasks
Tasks
 A task is a program component like a package and is declared
in a similar way inside a subprogram, block, package or in
another task body.
 The activation of a task is automatic.
 In the example presented before, the tasks become active
when the parent unit reaches the begin following the task
declaration.
 A tasks declared in the declarative part of a subprogram,
block or task body is said to depend on that unit.
 A unit cannot be left until all dependent tasks have
terminated.
 This termination rule ensures that objects declared in the
unit and therefore potentially visible to local tasks cannot
disappear while there exists a task which could access them.
5
Timing
Timing
 A delay can be used to suspend a thread
for a specified period of time:
delay 3.0;
This suspends a thread for 3 seconds.
 We can also use an absolute delay
statement:
delay until Some_Time;
Some_Time is of type Time (which is defined in
Ada.Calendar).
6
Communication and
Communication and
Synchronization
Synchronization
 Shared-variable or message passing
◦ Message passing can be asynchronous or synchronous
◦ For shared data, a popular model is a monitor
 A monitor can be considered as an object where each of its operation executes in
mutual exclusion (object has at least one lock)
 Condition Synchronization
◦ expresses a constraint on the ordering of execution of operations
 e.g., data cannot be removed from a buffer until data has been placed in the buffer
◦ Monitors provide condition variables (to implement condition
synchronization)
 In Ada all these models are allowed
◦ Synchronous communication by rendezvouz
◦ Asynchronous communication and shared data with protected objects
◦ Condition synchronization in both
7
Rendezvous
Rendezvous
 A rendezvous between two tasks occurs as a consequence of
one task calling an entry declared in another.
 An entry is declared in a task specification in a similar way to
a procedure in a package specification.
 An entry may have in, out and in out parameters in the same
way as a procedure.
 An entry cannot have access parameters nor can it have a
result like a function.
 An entry is called in a similar way to a procedure
 A task name cannot appear in a use clause and so the dotted
notation is necessary.
 The statements to be obeyed during the rendezvous are
described by corresponding accept statements in the body of
the task:
8
Rendezvous
Rendezvous
9
task Buffer is
entry Put(X: in Item);
entry Get(X: out Item);
end Buffer;
task body Buffer is
V: Item;
begin
loop
accept Put(X: in Item) do
V := X;
end Put;
accept Get(X: out Item) do
X := V;
end Get;
end loop;
end Buffer;
procedure Call is
X: Item;
begin
Buffer.Put(X);
-- ...
Buffer.Get(X);
end Shopping;
Rendezvous
Rendezvous
 Several tasks may call Put and Get an
consequently may have to be queued.
 Every entry has a queue of tasks normally
processed in a first-in-first-out manner.
 The number of tasks on the queue of
entry E is given by E’Count, but this
attribute may only be used inside the
body of the task owning the entry.
 Each execution of an accept removes a
task from the queue.
10
Protected Objects
Protected Objects
 The holy grail of data sharing? 
 Consider the problem of protecting a variableV
from uncontrolled access.We may consider a
package with procedures to read and write.
11
package Protected_Variable is
procedure Read(X: out Item);
procedure Write(X: in Item);
end Protected_Variable;
package body Protected_Variable is
V: Item := initial_value;
procedure Read(X: out Item) is
begin
X := V;
end Read;
procedure Write(X: in Item) is
begin
V := X;
end Write;
end Protected_Variable;
Protected Objects
Protected Objects
 This solution is very unsatisfactory.
 Nothing prevents different tasks in our system
from calling Read andWrite simultaneously and
causing interference.
 Suppose that the type Item is a record giving
the coordinates of an aircraft:
type Item is
record
X_Coord: Float;
Y_Coord: Float;
end record;
12
Protected Objects
Protected Objects
13
Task B
Y: Item;
Protected_Variable.Read(Y);
Task A
X: Item := (X_Coord => 1.1,
Y_Coord => 2.1);
Protected_Variable.Write(X);
Protected Objects
Protected Objects
14
Task B
Y: Item;
Protected_Variable.Read(Y);
Task A
X: Item := (X_Coord => 1.1,
Y_Coord => 2.1);
protected_Variable.Write(X);
-- V.X_Coord := X.X_Coord;
-- V.Y_Coord := X.Y_Coord;
Protected Objects
Protected Objects
15
Task B
Y: Item;
Protected_Variable.Read(Y);
-- Y.X_Coord := V.X_Coord;
-- Y.Y_Coord := V.Y_Coord;
Task A
X: Item := (X_Coord => 1.1,
Y_Coord => 2.1);
protected_Variable.Write(X);
-- V.X_Coord := X.X_Coord;
-- V.Y_Coord := X.Y_Coord;
Protected Objects
Protected Objects
16
Task B
Y: Item;
protected_Variable.Read(Y);
-- Y.X_Coord := V.X_Coord;
-- Y.Y_Coord := V.Y_Coord;
Task A
X: Item := (X_Coord => 1.1,
Y_Coord => 2.1);
protected_Variable.Write(X);
-- V.X_Coord := X.X_Coord;
-- V.Y_Coord := X.Y_Coord;
Race Condition
Protected Objects
Protected Objects
 The solution is using a protected object instead
of a package.
 The protected object is divided in two parts:
◦ the visible part containing the specification of
subprograms.
◦ the private part which contains the hidden shared
data.
◦ unlike packages and tasks the bodies of protected
objects cannot declare any data (must be all defined
in the private part).
17
Protected Objects
Protected Objects
18
protected Protected_Variable is
procedure Read(X: out Item);
procedure Write(X: in Item);
private
V: Item := initial_value;
end Protected_Variable;
protected body Protected_Variable is
procedure Read(X: out Item) is
begin
X := V;
end Read;
procedure Write(X: in Item) is
begin
V := X;
end Write;
end Protected_Variable;
Protected Objects
Protected Objects
 Conditional synchronization
◦ Protected objects may have entries, as tasks
◦ Entries may have barriers (task entries may have guards,
but for a different purpose)
◦ If the barrier is false, the calling task is queued until
circunstances are such that the barrier is true (the lock is
released in the meanwhile).
◦ At the end of execution of an entry body (or procedure)
of the protected object, all barriers which have queued
tasks are re-evaluated thus possibly permiting the
processing of an entry call which had been queued from a
false barrier.
◦ At the end of functions the barrier is not reevaluated since
they cannot change the state o the protected object.
19
Protected Objects
Protected Objects
20
N: constant := 8;
type Index is mod N;
type Item_Array is array
(Index) of Item;
protected type Buffering is
entry Put(X: in Item);
entry Get(X: out Item);
private
A: Item_Array;
In_Ptr, Out_Ptr: Index := 0;
Count: Integer range 0..N:= 0;
end Buffering;
protected body Buffering is
entry Put(X: in item) when Count < N is
begin
A(In_Ptr) := X;
In_Ptr := In_Ptr + 1;
Count := Count + 1;
end Put;
entry Get(X: out Item) when Count > 0 is
begin
X:= A(Out_Ptr);
Out_Ptr:= Out_Ptr + 1;
Count := Count + 1;
end Get;
end Buffering;
My_Buffer: Buffering;
...
My_Buffer.Put(X);
My_Buffer.Get(X);
My_Buffer.Get(X);
Protected Objects
Protected Objects
 We have seen POs for:
◦ Protecting access to a shared variable
◦ Implementing a buffer
 Event signaling is also very easy
21
protected Event is
entry Wait;
procedure Signal;
private
Occurred: Boolean := False;
end Event;
protected body Event is
entry Wait when Occurred is
begin
Occurred := False;
end Wait;
procedure Signal is
begin
Occurred := True;
end Signal;
end Event;
Sporadic task:
loop
Event.Wait;
-- work
end loop;
Protected Objects
Protected Objects
 The general principle of a protected operation is that it
should be of short duration.
 This of course is left up to the programmer
 Potentially blocking operations are considered errors if
invoked during a protected action:
◦ an entry call;
◦ a delay;
◦ an abort;
◦ creating a task.
 Very complex concurrency tools can be built on top of
POs
◦ Also with requeue; entry families, nested calls
22
Select
Select
 A select statement in the receiving side of a
rendezvous allows
◦ a task to select from one of several rendezvous
◦ a task to accept rendezvous with timeouts (or
not wait at all)
 A select statement also allows a task to
perform timed or conditional entry calls (to
rendezvous or protected objects)
 And to do asynchronous transfer of control
(the good and evil of concurrency)
23
Select
Select
24
select
accept This(...) do
...
end;
or
accept That(...) do
...
end;
or
delay 10.0;
... -- time out statements
end select;
select
accept This(...) do
...
end;
or
-- guarded option
when Something_True =>
accept That(...) do
...
end;
else
... -- execute immediately if
-- no task calling
-- rendezvous
end select;
Select
Select
25
Operator.Call(“Put out fire”);
select
accept Acknowledge;
or
delay 60.0;
Fire_Brigade.Call;
end select;
Operator.Call(“Put out fire”);
select
accept Acknowledge;
else
delay 60.0;
Fire_Brigade.Call;
end select;
Different ?
Select
Select
 Timed and conditional calls
 ATC
26
select
Operator.Call(“Put out fire”);
or
delay 1*Minutes;
Fire_Brigade.Call;
end select;
select
Operator.Call(“Put out fire”);
else
Fire_Brigade.Call;
end select;
Result := Mandatory_Calculation;
select
delay until Deadline;
then abort
Result := Optional_Part;
end select;
Output(Result);
Select
Select
 ATC
◦ Mode change
27
loop
select
Mode_Manager.Wait_Change;
if current_mode = Normal then
current_mode := Emergency;
period := 5.0;
else
current_mode := Normal;
period := 50.0;
end if;
then abort
loop
-- do the job
-- careful with non abortable code
Next := Next + Period;
delay until Next;
end loop;
end select;
end loop;
Abort
Abort
 Do not use …
◦ … unless you need
 We can use the keyword abort to unconditionally terminate one
or more tasks.
 If a task is aborted then all tasks dependent upon are also aborted.
 The rendezvous and operations of a protected object are abort
deferred regions.
28
select
T.Closedown;
or
delay 60.0;
abort T;
end select;
Task T:
loop
select
accept Closedown;
-- clean up
exit loop;
else
-- do the job
end select;
Real-time
Real-time
 Ada is a complete concurrent language
 But up to know we have not dealt with
scheduling, dispatching and timing issues
 That is specified in a language Annex (D):
◦ Priorites
◦ Dispatching model
◦ Locking and queuing policies
◦ Monotonic time
◦ Task control
◦ Execution time timers
◦ Timing events
◦ Among other issues
29
Priorities
Priorities
 A task has a base priority and an active priority.
 The active priority is the one that is used to decide
which tasks get the processors and is never less than
the base priority.
 Unless a task is involved in some interaction with
another task or protected object, the active priority is
the same as the base priority.
 In the case of a rendezvous, the called task takes the
active priority of the caller if that is higher.
 In activation, a task takes the priority of the parent
task, if higher
 Type Priority is a subtype of Any_Priority which itself
is a subtype of Integer.
◦ The range of values of Priority is always at least 30.
30
Priorities
Priorities
31
procedure Shopping is
task Get_Salad is
pragma Priority(30);
end Get_Salad;
task body Get_Salad is
begin
Buy_Salad;
end Get_Salad;
task Get_Wine;
task body Get_Wine is
begin
Buy_Wine;
end Get_Wine;
begin
Buy_Meat;
end Shopping;
Priorities
Priorities
32
procedure Shopping is
task Get_Salad is
task body Get_Salad is
begin
Buy_Salad;
end Get_Salad;
task Get_Wine;
task body Get_Wine is
begin
Buy_Wine;
end Get_Wine;
begin
Set_Priority(30,Get_Salad’Identity);
Buy_Meat;
end Shopping;
Priorities
Priorities
 Protected objects also have priorities
◦ Used for priority ceiling protocols
◦ Ceilings can be dynamically changed
 That is dangerous but used, e.g., for mode changes
33
protected Event is
pragma Priority (Max);
entry Wait;
procedure Signal;
private
Occurred: Boolean := False;
end Event;
Dispatching models
Dispatching models
 From Ada 2005, it is possible to schedule a program with
different (but simultaneous) dispatching policies
 The following policies are defined
◦ FIFO_Whitin_Priorities – Within each priority level tasks are dealt
with on a first-in-first-out basis.A task may preempt a task of a
lower priority.
◦ Non_Preemptive_FIFO_Whitin_Priorities – Whitin each priority
level to which it applies tasks run to completion until they are
blocked or execute a delay statement.A task cannot be preempted
by one of higher priority.
◦ Round_Robin_Whitin_Priorities – Whitin each priority level tasks
are time-sliced with an interval that can be specified.
◦ EDF_Across_Priorities – This provides Earliest Deadline First
dispatching.The general idea is that across a range of priorities
levels, each task has a deadline and the one with the earliest
deadline is processed first.This policy has mathematically provable
advantages with respect to resource utilization.
34
Dispatching models
Dispatching models
 A single priority can be defined
 or different policies can be mixed in the same
application (but in different priority bands)
 It is a hierarchical model: first priority based, then
specific priority level policy
35
pragma Task_Dispatching_Policy(Round_Robin_Whitin_Priorities);
pragma Priority_Specific_Dispatching(Round_Robin_Whitin_Priority,1,1);
pragma Priority_Specific_Dispatching(EDF_Across_Priorities,2,10);
pragma Priority_Specific_Dispatching(FIFO_Whitin_Priority,11,24);
Dispatching models
Dispatching models
 Round robin: quantum is per priority level
 The deadline of a task for EDF is a property similar to
priority and can be set when the task is created:
 This ensures that the absolute deadline of the task
when it is created is equal to RD after its time of
creation.
 There is also a dynamic Set_Deadline procedure
36
procedure Set_Quantum (Pri : in System.Priority;
Quantum : in Ada.Real_Time.Time_Span);
task T is
pragma Relative_Deadline(RD);
…
Dispatching models
Dispatching models
 Deadlines can be used even without EDF
◦ Example deadline overrun:
37
loop
-- periodic task, priority dispatching
select
delay until Ada.Dispatching.EDF.Get_Deadline;
-- error recovery
then abort
-- code
end select;
Next := Next + Period;
delay until Next;
end loop;
Locking and queuing policies
Locking and queuing policies
 If the pragma Locking_Policy is used to specify
Ceiling_Locking by writing:
 Implements the Immediate Ceiling Priority Protocol
◦ A task using the PO will inherit the ceiling priority while
executing the protected operation.
◦ A calling task with higher active priority than the ceiling is not
permitted to execute the protected operation
◦ Deadlock free
 Queues can be handled by FIFO order or by priorities:
38
pragma Locking_Policy(Ceiling_Locking);
pragma Queuing_Policy(Priority_Queuing);
Locking and queuing policies
Locking and queuing policies
 If EDF is used, Ceiling Locking must be used
◦ Protected Objects access use a version of SRP, called
Preemption Level Control Protocol
◦ That is why EDF policy is EDF_Across_Priorities
◦ Priority levels and objects Ceilings are used for
preemption levels
◦ It also allows to shared data between different
dispatching policies
39
Clocks andTime
Clocks andTime
 We have seen that Ada supports the notion of a wall clock
(calendar time); for many applications, a clock based on UTC
(Coordinated UniversalTime) is sufficient
 Real-time systems often also require
◦ A monotonic clock which progresses at a constant rate and is
not subject to the insertion of extra ticks to reflect leap seconds
(as UTC clocks are).A constant rate is needed for control
algorithms which want to executed on a regular basis. Many
monotonic clocks are also relative to system startup and can be
used only to measure the passage of time, not calendar time
◦ Timers which can be paused, continued or reset (for example
the clock which counts down to the launch of the Space Shuttle)
◦ CPU execution time clocks which measure the amount of CPU
time that is being consumed by a particular thread or object
40
Time and Timers
Time and Timers
 The Real-Time Annex specifies two additional
clocks
◦ Monotonic time (Time and Time_Span)
◦ CPU_Time
 There are functions to convert between the different
clocks
◦ A direct relation may not be true
 Monotonic time
◦ Support 50 years programs, 1 millisecond ticks, 20 microseconds
resolution. No backward jumps
 The Annex also specifies additional timers (timing
events)
41
Time and Timers
Time and Timers
 CPU_Time measures the actual execution time
of each task
◦ A task may set several timers, dependent on
execution time
◦ Allows to detectWCET overrun but also to
implement more complex scheduling algorithms
 It is also possible to associate an execution time
budget with a group of tasks
◦ A timer can be set when the budget expires
42
Time and Timers
Time and Timers
 WCET overrun
43
protected WCET_Overrun is
entry Wait;
procedure Fire;
private
Occurred: Boolean := False;
end WCET_Overrun;
protected body WCET_Overrun is
entry Wait when Occurred is
begin
Occurred := False;
end Wait;
procedure Fire is
begin
Occurred := True;
end Signal;
end WCET_Overrun;
Ex_Timer:
Ada.Execution_Time.Timers.Timer(T'Access);
loop
-- periodic task
Set_Handler(Ex_Timer, WCET,
WCET_Overrun.Fire'Access);
select
WCET_Overrun.Wait;
-- error recovery
then abort
-- code
end select;
Cancel_Handler(Ex_Timer, Cancelled);
Next := Next + Period;
delay until Next;
end loop;
Timing Events
Timing Events
 Timing events measure real time rather than
execution time and can be used to trigger
events at specified real times.
 Allows to perform timing related operations
without tasks
◦ More efficient
◦ The hander is a protected procedure, thus not allowed to block
 Useful also for scheduling control
◦ Dual priority schemes
◦ Jitter avoidance
44
Timing Events
Timing Events
 Changing CPU
45
protected CPU_Change is
procedure Change;
end CPU_Change;
protected body CPU_Change is
procedure Change is
begin
Set_CPU(CPU_2, Task_ID);
end Signal;
end CPU_Change;
Switch: Timing_Event;
loop
-- periodic task
Set_CPU(CPU_1, Task_ID);
Switch.Set_Handler(
Change_Time,
CPU_Change.Change’Access);
-- code
Switch.Cancel_Handler(Cancelled);
Next := Next + Period;
delay until Next;
end loop;
Task Control
Task Control
 The Annex also specifies a mechanism to allow
a task to self-supend
◦ The Suspension_Object in Ada. Synchronous_Task_Control
◦ Procedures to Suspend_Until_True, and Set_True
 There is also a more dangerous mechanism for
suspending another task
◦ In package Ada.Asynchronous_Task_Control
◦ Procedures Hold and Continue allow task A to control the
execution of task B
46
Task Control
Task Control
 Changing CPU
47
protected CPU_Change is
procedure Change;
procedure Wait;
end CPU_Change;
protected body CPU_Change is
procedure Change is
begin
Continue(Task_ID);
Set_CPU(CPU_2, Task_ID);
end Signal;
procedure Wait is
begin
Hold(Task_ID);
end Wait;
end CPU_Change;
Wait, Switch: Timing_Event;
loop
-- periodic task
Set_CPU(CPU_1, Task_ID);
Wait.Set_Handler(Wait_Time,
CPU_Change.Wait’Access);
Switch.Set_Handler(Change_Time,
CPU_Change.Change’Access);
-- code
Switch1.Cancel_Handler(Cancelled);
Switch.Cancel_Handler(Cancelled);
Next := Next + Period;
delay until Next;
end loop;
Conclusion
Conclusion
 Extremely powerful concurrency model
 Safety as a fundamental language design
property
 Real-Time from the beginning of the
language specification
48

More Related Content

PDF
Java Enterprise Edition
PPT
Andy On Closures
PPTX
Javascripts hidden treasures BY - https://geekyants.com/
PDF
Latest C Interview Questions and Answers
PPTX
Storage Class Specifiers in C++
PPTX
2. Design patterns. part #2
PPT
Functions in c
Java Enterprise Edition
Andy On Closures
Javascripts hidden treasures BY - https://geekyants.com/
Latest C Interview Questions and Answers
Storage Class Specifiers in C++
2. Design patterns. part #2
Functions in c

Similar to Reliable and Concurrent Software: Ada presentation (20)

PDF
Password protected diary
PDF
Advanced C Programming Notes
PPT
SMI - Introduction to Java
PPTX
C++ theory
PDF
iPhone Seminar Part 2
PPT
ParaSail
PPT
VHDL Subprograms and Packages
PDF
(3) cpp procedural programming
PPTX
Java For Automation
PDF
JavaScript(Es5) Interview Questions & Answers
PPT
KEY
What's New In Python 2.5
PDF
Vhdl introduction
ODP
Bring the fun back to java
PPTX
My final requirement
PDF
1669958779195.pdf
RTF
Readme
PPTX
Switch case and looping jam
PPTX
Writing more complex models
PPTX
advance-dart.pptx
Password protected diary
Advanced C Programming Notes
SMI - Introduction to Java
C++ theory
iPhone Seminar Part 2
ParaSail
VHDL Subprograms and Packages
(3) cpp procedural programming
Java For Automation
JavaScript(Es5) Interview Questions & Answers
What's New In Python 2.5
Vhdl introduction
Bring the fun back to java
My final requirement
1669958779195.pdf
Readme
Switch case and looping jam
Writing more complex models
advance-dart.pptx
Ad

Recently uploaded (20)

PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
Current and future trends in Computer Vision.pptx
PPTX
Lecture Notes Electrical Wiring System Components
PPT
Project quality management in manufacturing
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
Digital Logic Computer Design lecture notes
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Construction Project Organization Group 2.pptx
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
web development for engineering and engineering
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PDF
composite construction of structures.pdf
PPTX
CH1 Production IntroductoryConcepts.pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
CYBER-CRIMES AND SECURITY A guide to understanding
Current and future trends in Computer Vision.pptx
Lecture Notes Electrical Wiring System Components
Project quality management in manufacturing
Foundation to blockchain - A guide to Blockchain Tech
Digital Logic Computer Design lecture notes
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
R24 SURVEYING LAB MANUAL for civil enggi
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Construction Project Organization Group 2.pptx
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
web development for engineering and engineering
Automation-in-Manufacturing-Chapter-Introduction.pdf
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
composite construction of structures.pdf
CH1 Production IntroductoryConcepts.pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Embodied AI: Ushering in the Next Era of Intelligent Systems
Ad

Reliable and Concurrent Software: Ada presentation

  • 1. Reliable and Concurrent Software Reliable and Concurrent Software Ada Ada PDEEC 2009/2010 1
  • 2. Context Context  1973: the DoD (world largest software buyer), was concerned in finding a programming language generally suitable for the department's requirements. ◦ Data: at that time 450 different languages were used in the DoD ◦ Non fulfilled the requirements  Approach: to develop a new language. ◦ International competition, 3 final candidates for development: Pascal, PL/I,Algol 68, Pascal (green language) won  Ada was named after Augusta Ada Byron (1815-52), daughter of the poet Lord Byron, and assistant of Charles Babbage ◦ Ada was the world’s first Programmer).  Ada becomes ISO standard 8652 in 1987 and a revised version was released in 95 (Ada 95). Further improvements were included in Ada 2005, and Ada 2012 is next 2
  • 3. Context Context  Goals ◦ Readability – professional programs are read much more often than they are written. ◦ Strong typing – More errors catch by the compiler. ◦ Programming in the large – mechanisms for encapsulation, separate compilation and library management are necessary for the writing of portable and maintainable programs of any size. ◦ Exception handling – Control unusual events. ◦ Data abstraction – extra portability and maintainability if the details of representation of data are kept separate from the specification of the logical operations on data. ◦ Object oriented programming – reuse, polymorphism, inheritance. ◦ Tasking – parallel activities. ◦ Generic units – logic independent of the types. ◦ Interface – able to communicate with systems possibly written in other languages.  We can do whatever we want – we just need to inform the compiler we know what we are doing 3
  • 4. Tasks Tasks  In Ada, parallel activities are defined by means of tasks.  A task is lexically described by a form very similar to a package.  It consists of the interface presented to other tasks and a body describing the dynamic behaviour of the task. 4 procedure Shopping is task Get_Salad; task body Get_Salad is begin Buy_Salad; end Get_Salad; task Get_Wine; task body Get_Wine is begin Buy_Wine; end Get_Wine; begin Buy_Meat; end Shopping;
  • 5. Tasks Tasks  A task is a program component like a package and is declared in a similar way inside a subprogram, block, package or in another task body.  The activation of a task is automatic.  In the example presented before, the tasks become active when the parent unit reaches the begin following the task declaration.  A tasks declared in the declarative part of a subprogram, block or task body is said to depend on that unit.  A unit cannot be left until all dependent tasks have terminated.  This termination rule ensures that objects declared in the unit and therefore potentially visible to local tasks cannot disappear while there exists a task which could access them. 5
  • 6. Timing Timing  A delay can be used to suspend a thread for a specified period of time: delay 3.0; This suspends a thread for 3 seconds.  We can also use an absolute delay statement: delay until Some_Time; Some_Time is of type Time (which is defined in Ada.Calendar). 6
  • 7. Communication and Communication and Synchronization Synchronization  Shared-variable or message passing ◦ Message passing can be asynchronous or synchronous ◦ For shared data, a popular model is a monitor  A monitor can be considered as an object where each of its operation executes in mutual exclusion (object has at least one lock)  Condition Synchronization ◦ expresses a constraint on the ordering of execution of operations  e.g., data cannot be removed from a buffer until data has been placed in the buffer ◦ Monitors provide condition variables (to implement condition synchronization)  In Ada all these models are allowed ◦ Synchronous communication by rendezvouz ◦ Asynchronous communication and shared data with protected objects ◦ Condition synchronization in both 7
  • 8. Rendezvous Rendezvous  A rendezvous between two tasks occurs as a consequence of one task calling an entry declared in another.  An entry is declared in a task specification in a similar way to a procedure in a package specification.  An entry may have in, out and in out parameters in the same way as a procedure.  An entry cannot have access parameters nor can it have a result like a function.  An entry is called in a similar way to a procedure  A task name cannot appear in a use clause and so the dotted notation is necessary.  The statements to be obeyed during the rendezvous are described by corresponding accept statements in the body of the task: 8
  • 9. Rendezvous Rendezvous 9 task Buffer is entry Put(X: in Item); entry Get(X: out Item); end Buffer; task body Buffer is V: Item; begin loop accept Put(X: in Item) do V := X; end Put; accept Get(X: out Item) do X := V; end Get; end loop; end Buffer; procedure Call is X: Item; begin Buffer.Put(X); -- ... Buffer.Get(X); end Shopping;
  • 10. Rendezvous Rendezvous  Several tasks may call Put and Get an consequently may have to be queued.  Every entry has a queue of tasks normally processed in a first-in-first-out manner.  The number of tasks on the queue of entry E is given by E’Count, but this attribute may only be used inside the body of the task owning the entry.  Each execution of an accept removes a task from the queue. 10
  • 11. Protected Objects Protected Objects  The holy grail of data sharing?   Consider the problem of protecting a variableV from uncontrolled access.We may consider a package with procedures to read and write. 11 package Protected_Variable is procedure Read(X: out Item); procedure Write(X: in Item); end Protected_Variable; package body Protected_Variable is V: Item := initial_value; procedure Read(X: out Item) is begin X := V; end Read; procedure Write(X: in Item) is begin V := X; end Write; end Protected_Variable;
  • 12. Protected Objects Protected Objects  This solution is very unsatisfactory.  Nothing prevents different tasks in our system from calling Read andWrite simultaneously and causing interference.  Suppose that the type Item is a record giving the coordinates of an aircraft: type Item is record X_Coord: Float; Y_Coord: Float; end record; 12
  • 13. Protected Objects Protected Objects 13 Task B Y: Item; Protected_Variable.Read(Y); Task A X: Item := (X_Coord => 1.1, Y_Coord => 2.1); Protected_Variable.Write(X);
  • 14. Protected Objects Protected Objects 14 Task B Y: Item; Protected_Variable.Read(Y); Task A X: Item := (X_Coord => 1.1, Y_Coord => 2.1); protected_Variable.Write(X); -- V.X_Coord := X.X_Coord; -- V.Y_Coord := X.Y_Coord;
  • 15. Protected Objects Protected Objects 15 Task B Y: Item; Protected_Variable.Read(Y); -- Y.X_Coord := V.X_Coord; -- Y.Y_Coord := V.Y_Coord; Task A X: Item := (X_Coord => 1.1, Y_Coord => 2.1); protected_Variable.Write(X); -- V.X_Coord := X.X_Coord; -- V.Y_Coord := X.Y_Coord;
  • 16. Protected Objects Protected Objects 16 Task B Y: Item; protected_Variable.Read(Y); -- Y.X_Coord := V.X_Coord; -- Y.Y_Coord := V.Y_Coord; Task A X: Item := (X_Coord => 1.1, Y_Coord => 2.1); protected_Variable.Write(X); -- V.X_Coord := X.X_Coord; -- V.Y_Coord := X.Y_Coord; Race Condition
  • 17. Protected Objects Protected Objects  The solution is using a protected object instead of a package.  The protected object is divided in two parts: ◦ the visible part containing the specification of subprograms. ◦ the private part which contains the hidden shared data. ◦ unlike packages and tasks the bodies of protected objects cannot declare any data (must be all defined in the private part). 17
  • 18. Protected Objects Protected Objects 18 protected Protected_Variable is procedure Read(X: out Item); procedure Write(X: in Item); private V: Item := initial_value; end Protected_Variable; protected body Protected_Variable is procedure Read(X: out Item) is begin X := V; end Read; procedure Write(X: in Item) is begin V := X; end Write; end Protected_Variable;
  • 19. Protected Objects Protected Objects  Conditional synchronization ◦ Protected objects may have entries, as tasks ◦ Entries may have barriers (task entries may have guards, but for a different purpose) ◦ If the barrier is false, the calling task is queued until circunstances are such that the barrier is true (the lock is released in the meanwhile). ◦ At the end of execution of an entry body (or procedure) of the protected object, all barriers which have queued tasks are re-evaluated thus possibly permiting the processing of an entry call which had been queued from a false barrier. ◦ At the end of functions the barrier is not reevaluated since they cannot change the state o the protected object. 19
  • 20. Protected Objects Protected Objects 20 N: constant := 8; type Index is mod N; type Item_Array is array (Index) of Item; protected type Buffering is entry Put(X: in Item); entry Get(X: out Item); private A: Item_Array; In_Ptr, Out_Ptr: Index := 0; Count: Integer range 0..N:= 0; end Buffering; protected body Buffering is entry Put(X: in item) when Count < N is begin A(In_Ptr) := X; In_Ptr := In_Ptr + 1; Count := Count + 1; end Put; entry Get(X: out Item) when Count > 0 is begin X:= A(Out_Ptr); Out_Ptr:= Out_Ptr + 1; Count := Count + 1; end Get; end Buffering; My_Buffer: Buffering; ... My_Buffer.Put(X); My_Buffer.Get(X); My_Buffer.Get(X);
  • 21. Protected Objects Protected Objects  We have seen POs for: ◦ Protecting access to a shared variable ◦ Implementing a buffer  Event signaling is also very easy 21 protected Event is entry Wait; procedure Signal; private Occurred: Boolean := False; end Event; protected body Event is entry Wait when Occurred is begin Occurred := False; end Wait; procedure Signal is begin Occurred := True; end Signal; end Event; Sporadic task: loop Event.Wait; -- work end loop;
  • 22. Protected Objects Protected Objects  The general principle of a protected operation is that it should be of short duration.  This of course is left up to the programmer  Potentially blocking operations are considered errors if invoked during a protected action: ◦ an entry call; ◦ a delay; ◦ an abort; ◦ creating a task.  Very complex concurrency tools can be built on top of POs ◦ Also with requeue; entry families, nested calls 22
  • 23. Select Select  A select statement in the receiving side of a rendezvous allows ◦ a task to select from one of several rendezvous ◦ a task to accept rendezvous with timeouts (or not wait at all)  A select statement also allows a task to perform timed or conditional entry calls (to rendezvous or protected objects)  And to do asynchronous transfer of control (the good and evil of concurrency) 23
  • 24. Select Select 24 select accept This(...) do ... end; or accept That(...) do ... end; or delay 10.0; ... -- time out statements end select; select accept This(...) do ... end; or -- guarded option when Something_True => accept That(...) do ... end; else ... -- execute immediately if -- no task calling -- rendezvous end select;
  • 25. Select Select 25 Operator.Call(“Put out fire”); select accept Acknowledge; or delay 60.0; Fire_Brigade.Call; end select; Operator.Call(“Put out fire”); select accept Acknowledge; else delay 60.0; Fire_Brigade.Call; end select; Different ?
  • 26. Select Select  Timed and conditional calls  ATC 26 select Operator.Call(“Put out fire”); or delay 1*Minutes; Fire_Brigade.Call; end select; select Operator.Call(“Put out fire”); else Fire_Brigade.Call; end select; Result := Mandatory_Calculation; select delay until Deadline; then abort Result := Optional_Part; end select; Output(Result);
  • 27. Select Select  ATC ◦ Mode change 27 loop select Mode_Manager.Wait_Change; if current_mode = Normal then current_mode := Emergency; period := 5.0; else current_mode := Normal; period := 50.0; end if; then abort loop -- do the job -- careful with non abortable code Next := Next + Period; delay until Next; end loop; end select; end loop;
  • 28. Abort Abort  Do not use … ◦ … unless you need  We can use the keyword abort to unconditionally terminate one or more tasks.  If a task is aborted then all tasks dependent upon are also aborted.  The rendezvous and operations of a protected object are abort deferred regions. 28 select T.Closedown; or delay 60.0; abort T; end select; Task T: loop select accept Closedown; -- clean up exit loop; else -- do the job end select;
  • 29. Real-time Real-time  Ada is a complete concurrent language  But up to know we have not dealt with scheduling, dispatching and timing issues  That is specified in a language Annex (D): ◦ Priorites ◦ Dispatching model ◦ Locking and queuing policies ◦ Monotonic time ◦ Task control ◦ Execution time timers ◦ Timing events ◦ Among other issues 29
  • 30. Priorities Priorities  A task has a base priority and an active priority.  The active priority is the one that is used to decide which tasks get the processors and is never less than the base priority.  Unless a task is involved in some interaction with another task or protected object, the active priority is the same as the base priority.  In the case of a rendezvous, the called task takes the active priority of the caller if that is higher.  In activation, a task takes the priority of the parent task, if higher  Type Priority is a subtype of Any_Priority which itself is a subtype of Integer. ◦ The range of values of Priority is always at least 30. 30
  • 31. Priorities Priorities 31 procedure Shopping is task Get_Salad is pragma Priority(30); end Get_Salad; task body Get_Salad is begin Buy_Salad; end Get_Salad; task Get_Wine; task body Get_Wine is begin Buy_Wine; end Get_Wine; begin Buy_Meat; end Shopping;
  • 32. Priorities Priorities 32 procedure Shopping is task Get_Salad is task body Get_Salad is begin Buy_Salad; end Get_Salad; task Get_Wine; task body Get_Wine is begin Buy_Wine; end Get_Wine; begin Set_Priority(30,Get_Salad’Identity); Buy_Meat; end Shopping;
  • 33. Priorities Priorities  Protected objects also have priorities ◦ Used for priority ceiling protocols ◦ Ceilings can be dynamically changed  That is dangerous but used, e.g., for mode changes 33 protected Event is pragma Priority (Max); entry Wait; procedure Signal; private Occurred: Boolean := False; end Event;
  • 34. Dispatching models Dispatching models  From Ada 2005, it is possible to schedule a program with different (but simultaneous) dispatching policies  The following policies are defined ◦ FIFO_Whitin_Priorities – Within each priority level tasks are dealt with on a first-in-first-out basis.A task may preempt a task of a lower priority. ◦ Non_Preemptive_FIFO_Whitin_Priorities – Whitin each priority level to which it applies tasks run to completion until they are blocked or execute a delay statement.A task cannot be preempted by one of higher priority. ◦ Round_Robin_Whitin_Priorities – Whitin each priority level tasks are time-sliced with an interval that can be specified. ◦ EDF_Across_Priorities – This provides Earliest Deadline First dispatching.The general idea is that across a range of priorities levels, each task has a deadline and the one with the earliest deadline is processed first.This policy has mathematically provable advantages with respect to resource utilization. 34
  • 35. Dispatching models Dispatching models  A single priority can be defined  or different policies can be mixed in the same application (but in different priority bands)  It is a hierarchical model: first priority based, then specific priority level policy 35 pragma Task_Dispatching_Policy(Round_Robin_Whitin_Priorities); pragma Priority_Specific_Dispatching(Round_Robin_Whitin_Priority,1,1); pragma Priority_Specific_Dispatching(EDF_Across_Priorities,2,10); pragma Priority_Specific_Dispatching(FIFO_Whitin_Priority,11,24);
  • 36. Dispatching models Dispatching models  Round robin: quantum is per priority level  The deadline of a task for EDF is a property similar to priority and can be set when the task is created:  This ensures that the absolute deadline of the task when it is created is equal to RD after its time of creation.  There is also a dynamic Set_Deadline procedure 36 procedure Set_Quantum (Pri : in System.Priority; Quantum : in Ada.Real_Time.Time_Span); task T is pragma Relative_Deadline(RD); …
  • 37. Dispatching models Dispatching models  Deadlines can be used even without EDF ◦ Example deadline overrun: 37 loop -- periodic task, priority dispatching select delay until Ada.Dispatching.EDF.Get_Deadline; -- error recovery then abort -- code end select; Next := Next + Period; delay until Next; end loop;
  • 38. Locking and queuing policies Locking and queuing policies  If the pragma Locking_Policy is used to specify Ceiling_Locking by writing:  Implements the Immediate Ceiling Priority Protocol ◦ A task using the PO will inherit the ceiling priority while executing the protected operation. ◦ A calling task with higher active priority than the ceiling is not permitted to execute the protected operation ◦ Deadlock free  Queues can be handled by FIFO order or by priorities: 38 pragma Locking_Policy(Ceiling_Locking); pragma Queuing_Policy(Priority_Queuing);
  • 39. Locking and queuing policies Locking and queuing policies  If EDF is used, Ceiling Locking must be used ◦ Protected Objects access use a version of SRP, called Preemption Level Control Protocol ◦ That is why EDF policy is EDF_Across_Priorities ◦ Priority levels and objects Ceilings are used for preemption levels ◦ It also allows to shared data between different dispatching policies 39
  • 40. Clocks andTime Clocks andTime  We have seen that Ada supports the notion of a wall clock (calendar time); for many applications, a clock based on UTC (Coordinated UniversalTime) is sufficient  Real-time systems often also require ◦ A monotonic clock which progresses at a constant rate and is not subject to the insertion of extra ticks to reflect leap seconds (as UTC clocks are).A constant rate is needed for control algorithms which want to executed on a regular basis. Many monotonic clocks are also relative to system startup and can be used only to measure the passage of time, not calendar time ◦ Timers which can be paused, continued or reset (for example the clock which counts down to the launch of the Space Shuttle) ◦ CPU execution time clocks which measure the amount of CPU time that is being consumed by a particular thread or object 40
  • 41. Time and Timers Time and Timers  The Real-Time Annex specifies two additional clocks ◦ Monotonic time (Time and Time_Span) ◦ CPU_Time  There are functions to convert between the different clocks ◦ A direct relation may not be true  Monotonic time ◦ Support 50 years programs, 1 millisecond ticks, 20 microseconds resolution. No backward jumps  The Annex also specifies additional timers (timing events) 41
  • 42. Time and Timers Time and Timers  CPU_Time measures the actual execution time of each task ◦ A task may set several timers, dependent on execution time ◦ Allows to detectWCET overrun but also to implement more complex scheduling algorithms  It is also possible to associate an execution time budget with a group of tasks ◦ A timer can be set when the budget expires 42
  • 43. Time and Timers Time and Timers  WCET overrun 43 protected WCET_Overrun is entry Wait; procedure Fire; private Occurred: Boolean := False; end WCET_Overrun; protected body WCET_Overrun is entry Wait when Occurred is begin Occurred := False; end Wait; procedure Fire is begin Occurred := True; end Signal; end WCET_Overrun; Ex_Timer: Ada.Execution_Time.Timers.Timer(T'Access); loop -- periodic task Set_Handler(Ex_Timer, WCET, WCET_Overrun.Fire'Access); select WCET_Overrun.Wait; -- error recovery then abort -- code end select; Cancel_Handler(Ex_Timer, Cancelled); Next := Next + Period; delay until Next; end loop;
  • 44. Timing Events Timing Events  Timing events measure real time rather than execution time and can be used to trigger events at specified real times.  Allows to perform timing related operations without tasks ◦ More efficient ◦ The hander is a protected procedure, thus not allowed to block  Useful also for scheduling control ◦ Dual priority schemes ◦ Jitter avoidance 44
  • 45. Timing Events Timing Events  Changing CPU 45 protected CPU_Change is procedure Change; end CPU_Change; protected body CPU_Change is procedure Change is begin Set_CPU(CPU_2, Task_ID); end Signal; end CPU_Change; Switch: Timing_Event; loop -- periodic task Set_CPU(CPU_1, Task_ID); Switch.Set_Handler( Change_Time, CPU_Change.Change’Access); -- code Switch.Cancel_Handler(Cancelled); Next := Next + Period; delay until Next; end loop;
  • 46. Task Control Task Control  The Annex also specifies a mechanism to allow a task to self-supend ◦ The Suspension_Object in Ada. Synchronous_Task_Control ◦ Procedures to Suspend_Until_True, and Set_True  There is also a more dangerous mechanism for suspending another task ◦ In package Ada.Asynchronous_Task_Control ◦ Procedures Hold and Continue allow task A to control the execution of task B 46
  • 47. Task Control Task Control  Changing CPU 47 protected CPU_Change is procedure Change; procedure Wait; end CPU_Change; protected body CPU_Change is procedure Change is begin Continue(Task_ID); Set_CPU(CPU_2, Task_ID); end Signal; procedure Wait is begin Hold(Task_ID); end Wait; end CPU_Change; Wait, Switch: Timing_Event; loop -- periodic task Set_CPU(CPU_1, Task_ID); Wait.Set_Handler(Wait_Time, CPU_Change.Wait’Access); Switch.Set_Handler(Change_Time, CPU_Change.Change’Access); -- code Switch1.Cancel_Handler(Cancelled); Switch.Cancel_Handler(Cancelled); Next := Next + Period; delay until Next; end loop;
  • 48. Conclusion Conclusion  Extremely powerful concurrency model  Safety as a fundamental language design property  Real-Time from the beginning of the language specification 48

Editor's Notes

  • #7: Messages are directly passed between tasks by a mechanism known as the redezvous. This system is similar to the human situation where two people meet, perform a transaction and then go on independently.