course teacher: d. m. akbar hussain - aalborg...

36
DE5 Thursday, September 23, 2010 Real-time Embedded System Programming 1 Real Real-Time Time Embedded System Programming Embedded System Programming Embedded System Programming Embedded System Programming Course Teacher: D. M. Akbar Hussain Course Teacher: D. M. Akbar Hussain Dr. D. M. Akbar Hussain Department of Electronic Systems 1 DE5 DE5-2010 2010 – Lessen # 3 Lessen # 3 1 1 Real Real Time System Design Time System Design 1. 1. Real Real- -Time System Design Time System Design 2. 2. Real Time Operating System Real Time Operating System 3. 3. Scheduling Scheduling 4. 4. Projects: Projects: Dr. D. M. Akbar Hussain Department of Electronic Systems 2 4. 4. Projects: Projects: Hardware Hardware Software Software

Upload: others

Post on 05-Aug-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 1

RealReal--Time Time Embedded System ProgrammingEmbedded System ProgrammingEmbedded System ProgrammingEmbedded System Programming

Course Teacher: D. M. Akbar HussainCourse Teacher: D. M. Akbar Hussain

Dr. D. M. Akbar Hussain

Department of Electronic Systems 1

DE5DE5--2010 2010 –– Lessen # 3Lessen # 3

11 RealReal Time System DesignTime System Design1.1. RealReal--Time System DesignTime System Design

2.2. Real Time Operating SystemReal Time Operating System

3.3. SchedulingScheduling

4.4. Projects:Projects:

Dr. D. M. Akbar Hussain

Department of Electronic Systems 2

4.4. Projects:Projects:

•• HardwareHardware•• SoftwareSoftware

Page 2: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 2

RealReal--Time System DesignTime System Design

Dr. D. M. Akbar Hussain

Department of Electronic Systems 3

ObjectivesObjectives

•• To explain the concept of aTo explain the concept of a realreal--time systemtime system and why these systems areand why these systems areTo explain the concept of a To explain the concept of a realreal time system time system and why these systems are and why these systems are usually implemented as concurrent usually implemented as concurrent processes.processes.

•• To describe a To describe a design process design process for realfor real--time time systems.systems.

•• To explain the To explain the role of a realrole of a real--time operating time operating systemsystem..

•• To introduce generic process architectures To introduce generic process architectures for:for:

Dr. D. M. Akbar Hussain

Department of Electronic Systems 4

•• MonitoringMonitoring•• Control Control •• Data Data AAcquisition Systems.cquisition Systems.

©Ian Sommerville

Page 3: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 3

Topics Topics CoveredCovered

•• System System DesignDesign•• RealReal--time time Operating SystemsOperating Systems•• Monitoring and Monitoring and Control Control SSystemsystems•• Data Data Acquisition Acquisition SSystemsystems

Dr. D. M. Akbar Hussain

Department of Electronic Systems 5©Ian Sommerville

RealReal--Time System FeaturesTime System Features

Timing Constraints: Timing Constraints: •• Timing Constraints: Timing Constraints: Not only correct but on timeNot only correct but on time

•• Concurrency:Concurrency:Interleaving or parallel executionInterleaving or parallel execution

•• reliability: reliability: Ho often a s stem failsHo often a s stem fails

Dr. D. M. Akbar Hussain

Department of Electronic Systems 6

How often a system failsHow often a system fails

•• Fault tolerance: Fault tolerance: Recognition and handling of errorsRecognition and handling of errors

Page 4: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 4

RealReal--Time System’s JobTime System’s Job

•• Monitor Monitor and and Control Control the environment.the environment.

•• Inevitably associated with hardware Inevitably associated with hardware devices:devices:

–– Sensors: Sensors: Collect data from the system Collect data from the system environment.environment.

–– Actuators: Actuators: Change (in some way) the system's Change (in some way) the system's environment.environment.

Ti i Ti i iti liti l

Dr. D. M. Akbar Hussain

Department of Electronic Systems 7

•• Time is Time is critical:critical:RealReal--time time systems systems MUST MUST respond respond within specified times.within specified times.

©Ian Sommerville

DefinitionDefinition

•• AA RealReal--TimeTime SSystemystem isis aa Hardware/SoftwareHardware/Software systemsystem wherewhere thethe correctcorrectfunctioningfunctioning ofof thethe systemsystem dependsdepends onon thethe resultsresults producedproduced byby thethe systemsystemandand thethe timetime atat whichwhich thesethese resultsresults areare producedproduced..

•• AA SSoftoft RealReal--TimeTime SystemSystem isis aa systemsystem whosewhose operationoperation isis degradeddegraded ifif resultsresultsareare notnot producedproduced accordingaccording toto thethe specifiedspecified timingtiming requirementsrequirements..

•• AA HHardard RealReal--TimeTime SSystemystem isis aa systemsystem whosewhose operationoperation isis incorrectincorrect ifif

Dr. D. M. Akbar Hussain

Department of Electronic Systems 8

yy yy ppresultsresults areare notnot producedproduced accordingaccording toto thethe timingtiming specificationspecification..

©Ian Sommerville

Page 5: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 5

Stimulus/Response SystemsStimulus/Response Systems

•• Given a stimulus, the system must produce a Given a stimulus, the system must produce a response response within a within a specified timespecified time..

•• Periodic stimuli. Periodic stimuli. Stimuli which occur at Stimuli which occur at predictable predictable time time intervalsintervals–– For example, a temperature sensor may be polled 10 times per secondFor example, a temperature sensor may be polled 10 times per second..

•• AperiodicAperiodic stimuli. stimuli. Stimuli which occur at Stimuli which occur at unpredictable times unpredictable times intervalsintervals–– For example, a system power failure may trigger an For example, a system power failure may trigger an interrupt interrupt which must be processed by which must be processed by

th tth t

Dr. D. M. Akbar Hussain

Department of Electronic Systems 9

the system.the system.

©Ian Sommerville

Architectural Architectural ConsiderationsConsiderations

•• BecauseBecause ofof thethe needneed toto respondrespond toto timingtiming demandsdemands mademade byby differentdifferentstimuli/responsesstimuli/responses,, thethe systemsystem architecturearchitecture mustmust allowallow forfor fastfast switchingswitching betweenbetweenstimulusstimulus handlershandlers..

•• TimingTiming demandsdemands ofof differentdifferent stimulistimuli areare differentdifferent soso aa simplesimple sequentialsequential looploop isis notnotusuallyusually adequateadequate..

•• RealReal timetime systemssystems areare thereforetherefore usuallyusually designeddesigned asas cooperatingcooperating processesprocesses withwith aa

Dr. D. M. Akbar Hussain

Department of Electronic Systems 10

•• RealReal--timetime systemssystems areare thereforetherefore usuallyusually designeddesigned asas cooperatingcooperating processesprocesses withwith aarealreal--timetime executiveexecutive controllingcontrolling thesethese processesprocesses..

©Ian Sommerville

Page 6: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 6

A A RealReal--Time System Time System MModelodel

SensorSensorSensor SensorSensorSensor

Real-TimeControl System

SensorSensorSensor SensorSensorSensor

Dr. D. M. Akbar Hussain

Department of Electronic Systems 11

ActuatorActuator ActuatorActuator

©Ian Sommerville

Sensor/Actuator Sensor/Actuator PProcessesrocesses

Data Actuator

Actuator

Sensor

Sensor

Stimulus Response

Dr. D. M. Akbar Hussain

Department of Electronic Systems 12

Dataprocessor

Actuatorcontrol

Sensorcontrol

©Ian Sommerville

Page 7: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 7

System System ElementsElements

•• Sensor control processesSensor control processes–– Collect information from sensors. May buffer information collected in response Collect information from sensors. May buffer information collected in response

to a sensor stimulusto a sensor stimulus..

•• Data processorData processor–– Carries out processing of collected information and computes the system Carries out processing of collected information and computes the system

responseresponse..

Dr. D. M. Akbar Hussain

Department of Electronic Systems 13

•• Actuator control processesActuator control processes–– Generates control signals for the actuators.Generates control signals for the actuators.

©Ian Sommerville

RealReal--Time ProgrammingTime Programming

•• HardHard--realreal timetime systemssystems maymay havehave toto bebe programmedprogrammed inin assemblyassemblylanguagelanguage toto ensureensure thatthat deadlinesdeadlines areare metmet..

•• LanguagesLanguages suchsuch asas CC allowallow efficientefficient programsprograms toto bebe writtenwritten butbut dodo notnothavehave constructsconstructs toto supportsupport concurrencyconcurrency oror sharedshared resourceresource managementmanagement..

Dr. D. M. Akbar Hussain

Department of Electronic Systems 14©Ian Sommerville

Page 8: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 8

Java as a Java as a RealReal--time time LLanguageanguage

•• Java supports lightweight concurrency (threads and synchronized methods) andJava supports lightweight concurrency (threads and synchronized methods) and•• Java supports lightweight concurrency (threads and synchronized methods) and Java supports lightweight concurrency (threads and synchronized methods) and can be used for some can be used for some soft realsoft real--time systemstime systems..

•• Java 2.0 is not suitable for Java 2.0 is not suitable for Hard Hard RT programming but realRT programming but real--time versions of Java are time versions of Java are now available that address problems such now available that address problems such as:as:

–– Not possible to specify thread execution Not possible to specify thread execution time.time.–– Different timing in different virtual Different timing in different virtual machines.machines.–– Uncontrollable garbage Uncontrollable garbage collection.collection.–– Not possible to discover queue sizes for shared Not possible to discover queue sizes for shared resources.resources.

Dr. D. M. Akbar Hussain

Department of Electronic Systems 15

p qp q–– Not possible to access system Not possible to access system hardware.hardware.–– Not possible to do space or timing analysis.Not possible to do space or timing analysis.

©Ian Sommerville

How To: System How To: System DDesignesign

•• DesignDesign bothboth thethe hardwarehardware andand thethe softwaresoftware associatedassociated withwith systemsystem..

•• PartitionPartition functionsfunctions toto eithereither hardwarehardware oror softwaresoftware..

•• DesignDesign decisionsdecisions shouldshould bebe mademade onon thethe basisbasis ofof NonNon--FunctionalFunctional systemsystemrequirementsrequirements..

H dH d d lid li b ttb tt ff b tb t hh ii

Dr. D. M. Akbar Hussain

Department of Electronic Systems 16

•• HardwareHardware deliversdelivers betterbetter performanceperformance butbut havehave issuesissues::

•• PotentiallyPotentially LLongeronger DevelopmentDevelopment•• LessLess ScopeScope forfor ChangeChange..

©Ian Sommerville

Page 9: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 9

Procedure to Design RProcedure to Design R--T SystemsT Systems

•• IdentifyIdentify thethe stimulistimuli toto bebe processedprocessed andand thethe requiredrequired responsesresponses toto thesethesestimulistimuli..

•• ForFor eacheach stimulusstimulus andand responseresponse,, identifyidentify thethe timingtiming constraintsconstraints..

•• AggregateAggregate thethe stimulusstimulus andand responseresponse processingprocessing intointo concurrentconcurrentAA bb i t di t d ithith hh ll ff ti lti l dd

Dr. D. M. Akbar Hussain

Department of Electronic Systems 17

processesprocesses.. AA processprocess maymay bebe associatedassociated withwith eacheach classclass ofof stimulusstimulus andandresponseresponse..

©Ian Sommerville

Procedure to Design RProcedure to Design R--T SystemsT Systems

•• DesignDesign algorithmsalgorithms toto processprocess eacheach classclass ofof stimulusstimulus andandresponseresponse.. TheseThese mustmust meetmeet thethe givengiven timingtiming requirementsrequirements..

•• DesignDesign aa schedulingscheduling systemsystem whichwhich willwill ensureensure thatthat processesprocessesareare startedstarted inin timetime toto meetmeet theirtheir deadlinesdeadlines..

Dr. D. M. Akbar Hussain

Department of Electronic Systems 18

•• IntegrateIntegrate usingusing aa realreal--timetime operatingoperating systemsystem..

©Ian Sommerville

Page 10: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 10

ConstraintsConstraints

•• MayMay requirerequire extensiveextensive analysis,analysis, simulationsimulation andand experimentexperiment toto ensureensure thatthatthesethese areare metmet byby thethe systemsystem..

•• MayMay meanmean thatthat certaincertain designdesign strategiesstrategies suchsuch asas objectobject--orientedoriented designdesigncannotcannot bebe usedused becausebecause ofof thethe additionaladditional overheadoverhead involvedinvolved..

•• MayMay meanmean thatthat lowlow--levellevel programmingprogramming languagelanguage featuresfeatures havehave toto bebe usedusedforfor performanceperformance reasonsreasons

Dr. D. M. Akbar Hussain

Department of Electronic Systems 19

forfor performanceperformance reasonsreasons..

©Ian Sommerville

System System MModellingodelling

S tS t d llid lli h lh l thth l tl t tt d t dd t d thth f ti litf ti lit ff thth•• SystemSystem modellingmodelling helpshelps thethe analystanalyst toto understandunderstand thethe functionalityfunctionality ofof thethesystemsystem andand modelsmodels areare usedused toto communicatecommunicate withwith customerscustomers..

•• DifferentDifferent modelsmodels presentpresent thethe systemsystem fromfrom differentdifferent perspectivesperspectives::

–– ExternalExternal perspectiveperspective showingshowing thethe system’ssystem’s contextcontext oror environmentenvironment;;–– BehaviouralBehavioural perspectiveperspective showingshowing thethe behaviourbehaviour ofof thethe systemsystem;;–– StructuralStructural perspectiveperspective showingshowing thethe systemsystem oror datadata architecturearchitecture..

Dr. D. M. Akbar Hussain

Department of Electronic Systems 20

p pp p gg yy

©Ian Sommerville

Page 11: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 11

Context of an ATM MachineContext of an ATM Machine

Dr. D. M. Akbar Hussain

Department of Electronic Systems 21©Ian Sommerville

Behavioural ModelBehavioural Model

•• Behavioural models are used to describe the overall behaviour of a system.Behavioural models are used to describe the overall behaviour of a system.

•• Two types of behavioural model are:Two types of behavioural model are:

–– Data processing models Data processing models that show how data is processed as it moves through the system;that show how data is processed as it moves through the system;–– State machine models State machine models that show the systems response to events.that show the systems response to events.

•• These modelsThese models show different perspectivesshow different perspectives so both of them are required to describe theso both of them are required to describe the

Dr. D. M. Akbar Hussain

Department of Electronic Systems 22©Ian Sommerville

•• These models These models show different perspectives show different perspectives so both of them are required to describe the so both of them are required to describe the system’s behaviour.system’s behaviour.

Page 12: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 12

Behavioural Model ExampleBehavioural Model Example

Completeorder form

Orderdetails +

blankor der form

Validateorder

Recordor der

Send tosupplier

Adjustavailablebudget

Completedorder form

Signedorder for m

Signedorder form

Checked andsigned or der

+ or dernotifica tion

Orderamount

Signedorder form

Orderdetails

Dr. D. M. Akbar Hussain

Department of Electronic Systems 23©Ian Sommerville

Budgetfile

Ordersfile

+ accountdetails

Structural MethodsStructural Methods

•• Structured methods incorporate system modelling as an inherent part of the method.Structured methods incorporate system modelling as an inherent part of the method.

•• Methods define a set of models, a process for deriving these models and rules and Methods define a set of models, a process for deriving these models and rules and guidelines that should apply to the models.guidelines that should apply to the models.

•• CASE tools support system modelling as part of a structured method.CASE tools support system modelling as part of a structured method.

Dr. D. M. Akbar Hussain

Department of Electronic Systems 24©Ian Sommerville

Page 13: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 13

Components of a CASE Tool for Structured Components of a CASE Tool for Structured Method SupportMethod Support

StructuredData Repor t

Centralinformationrepository

Codegenerator

Querylanguagefacilities

diagrammingtools

Datadictionary generation

facilities

Dr. D. M. Akbar Hussain

Department of Electronic Systems 25©Ian Sommerville

Design, analysisand checking

tools

Formscrea tion

tools

Import/e xportfacilities

System Model TypesSystem Model Types

•• Data processing model Data processing model showing how the data is processed at different stages.showing how the data is processed at different stages.•• Composition model Composition model showing how entities are composed of other entities.showing how entities are composed of other entities.•• Architectural model Architectural model showing principal subshowing principal sub--systems.systems.•• Classification model Classification model showing how entities have common characteristics.showing how entities have common characteristics.•• Stimulus/ResponseStimulus/Response model showing the system’s reaction to events.model showing the system’s reaction to events.

Dr. D. M. Akbar Hussain

Department of Electronic Systems 26

Page 14: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 14

RealReal--Time System ModellingTime System Modelling

ThTh ff tff t ff ti lti l ii ll titi tt t it i t itit iti ff•• TheThe effecteffect ofof aa stimulusstimulus inin aa realreal--timetime systemsystem maymay triggertrigger aa transitiontransition fromfromoneone statestate toto anotheranother..

•• FiniteFinite statestate machinesmachines cancan bebe usedused forfor modellingmodelling realreal--timetime systemssystems..

•• However,However, FSMFSM modelsmodels lacklack structurestructure.. EvenEven simplesimple systemssystems cancan havehave aacomplexcomplex modelmodel..

Dr. D. M. Akbar Hussain

Department of Electronic Systems 27

•• TheThe UMLUML includesincludes notationsnotations forfor definingdefining statestate machinemachine modelsmodels

©Ian Sommerville

Petrol Petrol Pump State Pump State MModelodel

Dr. D. M. Akbar Hussain

Department of Electronic Systems 28©Ian Sommerville

Page 15: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 15

RealReal--Time Operating Time Operating SSystemsystems

R lR l titi titi tt i li di li d titi tt hi hhi h•• RealReal--timetime operatingoperating systemssystems areare specialisedspecialised operatingoperating systemssystems whichwhichmanagemanage thethe processesprocesses inin thethe RTSRTS..

•• ResponsibleResponsible forfor processprocess managementmanagement andand resourceresource (processor(processor andandmemory)memory) allocationallocation..

•• MayMay bebe basedbased onon aa standardstandard kernelkernel whichwhich isis usedused unchangedunchanged oror modifiedmodifiedforfor aa particularparticular applicationapplication..

Dr. D. M. Akbar Hussain

Department of Electronic Systems 29

pp pppp

•• DoDo notnot normallynormally includeinclude facilitiesfacilities suchsuch asas filefile managementmanagement..

RT Operating RT Operating SSystem ystem CComponentsomponents

•• RealReal--time clocktime clock–– Provides information for process schedulingProvides information for process scheduling..

•• Interrupt handlerInterrupt handler–– Manages Manages aa--periodic periodic requests for servicerequests for service..

•• SchedulerScheduler–– Chooses the next process to be runChooses the next process to be run..

•• Resource managerResource manager–– Allocates memory and processor resourcesAllocates memory and processor resources..

Dr. D. M. Akbar Hussain

Department of Electronic Systems 30

y py p

•• DispatcherDispatcher–– Starts process execution.Starts process execution.

©Ian Sommerville

Page 16: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 16

NonNon--Stop System Stop System CComponentsomponents

•• Configuration Configuration ManagerManager–– Responsible for the dynamic reconfiguration of the Responsible for the dynamic reconfiguration of the system software system software and hardware. and hardware.

Hardware modules may be replaced and software upgraded without stopping the Hardware modules may be replaced and software upgraded without stopping the systemssystems..

•• Fault Fault ManagerManager–– Responsible for detecting software and hardware faults and Responsible for detecting software and hardware faults and taking taking appropriate actions appropriate actions

(e.g. switching to backup disks) to ensure that the system continues in operation.(e.g. switching to backup disks) to ensure that the system continues in operation.

Dr. D. M. Akbar Hussain

Department of Electronic Systems 31©Ian Sommerville

RealReal--Time Time OS OS ComponentsComponentsSchedulinginformation

Process resourceRequirements

Scheduler

Resourcemanager

Real-timeclock

Processesawaiting

resources

Interrupthandler

Availableresource

list

Dr. D. M. Akbar Hussain

Department of Electronic Systems 32

DespatcherReadylist

Processorlist

Executing pr ocess

Readyprocesses

Releasedresources

©Ian Sommerville

Page 17: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 17

Trade OffsTrade Offs

• Mono-lithic Kernel

• Pre-Emptive Kernel

• Scalability

• Memory Management

• Dedicated Vs General

Dr. D. M. Akbar Hussain

Department of Electronic Systems 33

• Dedicated Vs General

• Operating System vs Language runtime

Kernel Space Kernel Space vsvs User Space User Space vsvs Real Time Real Time SpaceSpace

Most modern processors allow programs to run in two different hardware protectionMost modern processors allow programs to run in two different hardware protectionlevels.

Linux calls these two levels kernel space and user space.

The latter have more protection against erroneous accesses to physical memory of I/Odevices.

The real-time Linux variants add a third layer, the real-time space.

Dr. D. M. Akbar Hussain

Department of Electronic Systems 34

y , p

This is in fact nothing else but a part of kernel space used, but used in a particular way.

Page 18: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 18

Monolithic Kernel Monolithic Kernel vsvs MicroMicro--Kernel.Kernel.

1. A monolithic kernel has all OS services (including device drivers, network stacks, file systems,etc.) running within the privileged mode of the processor.

2. A micro-kernel, on the other hand, uses the privileged mode only for really core services (taskmanagement and scheduling, inter-process communication, interrupt handling, and memorymanagement), and has most of the device drivers and OS services running as “normal” tasks.

3. The trade-off between both is as follows:

1. Monolithic kernel is easier to make more efficient (because OS services can runcompletely without switches from privileged to non-privileged mode).

2 Micro kernel is more difficult to crash (an error in a device driver that doesn’t run in

Dr. D. M. Akbar Hussain

Department of Electronic Systems 35

2. Micro-kernel is more difficult to crash (an error in a device driver that doesn t run inprivileged mode is less likely to cause a system halt than an error occurring in privilegedmode).

PrePre--emptive Kernelemptive Kernel

MostMost modernmodern operatingoperating systemssystems areare prepre--emptiveemptive..

ForFor exampleexample LinuxLinux waswas originallyoriginally aa nonnon--prepre--emptiveemptive kernelkernel:: aa kernelkernel spacespace tasktask cannotcannot bebeinterruptedinterrupted byby otherother kernelkernel spacespace tasks,tasks, oror byby useruser spacespace taskstasks..

TheThe kernelkernel isis “locked”“locked” asas longlong asas oneone kernelkernel functionfunction isis executingexecuting..

ThisThis usageusage ofof lockslocks makesmakes thethe designdesign ofof thethe kernelkernel simpler,simpler, butbut introducesintroduces inin--deterministicdeterministiclatencieslatencies whichwhich areare notnot tolerabletolerable inin anan RTOSRTOS

Dr. D. M. Akbar Hussain

Department of Electronic Systems 36

latencieslatencies whichwhich areare notnot tolerabletolerable inin anan RTOSRTOS..

Page 19: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 19

PrePre--emptive OSemptive OS

Dr. D. M. Akbar Hussain

Department of Electronic Systems 37

ScalabilityScalability

Scalability is much lessless ofof anan issueissue inin realreal--timetime applications,applications, because the goals are so different:

The desire behind scalable systems is to divide a large work load transparentlyover a number of available CPUs.

The desiredesire behindbehind realreal--timetime systems is that everything is controlled in a strictlydeterministic way.

Dr. D. M. Akbar Hussain

Department of Electronic Systems 38

Page 20: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 20

Memory ManagementMemory Management

Virtual memory and dynamic allocation and de-allocation of memory pages are amongst the mostcommonly used memory management services of a general purpose operating system.

However, this memory management induces overhead, and some simpler processors have no supportfor this memory management. On these processors (which power an enormous number of embeddedsystems!), all tasks share the same memory space, such that developers must take care of the properuse of that memory.

Also some real-time kernels (such as RTLinux) have all their tasks share the same address space

Dr. D. M. Akbar Hussain

Department of Electronic Systems 39

( ) p(even if the processor supports memory management), because this allows more efficient code.

Dedicated Dedicated VsVs GeneralGeneral

For many applications, it is worthwhile not to use a commercially or freely availableoperating system but write one that is optimised for the task at handoperating system, but write one that is optimised for the task at hand.

Examples are the operating systems for mobile phones, or Personal Digital Assistants.

Standard operating systems are too big, and they don’t have the specific signal processingsupport (speech and handwriting recognition) that is typical for these applications.

Some applications even don’t need an operating system at all. (For example, a simplevending machine).

Dr. D. M. Akbar Hussain

Department of Electronic Systems 40

The trade-offs here are: cost of development and decreased portability, against cost ofsmaller and cheaper embedded systems.

Page 21: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 21

Operating System Operating System VSVS Language RuntimeLanguage Runtime

Application programs make use of “lower-level” primitives to build their functionality ThisApplication programs make use of lower level primitives to build their functionality. Thisfunctionality can be offered by the operating system (via system calls), or by a programminglanguage (via language primitives and libraries).

Languages such as C++, Ada and Java offer lots of functionality this way: memory management,threading, task synchronization, exception handling, etc. This functionality is collected in a so-calledruntime.

The advantages of using a runtime are: its interface is portable over different operating systems, andit offers ready-to-use and/or safe solutions to common problems.

Dr. D. M. Akbar Hussain

Department of Electronic Systems 41

The disadvantages are that a runtime is in general “heavy”, not deterministic in execution time, andnot very configurable. These disadvantages are important in real-time and embedded contexts.

Process Process PriorityPriority

•• The processing of some types of stimuli must The processing of some types of stimuli must sometimes sometimes take prioritytake priority..

•• Interrupt level priority. Interrupt level priority. Highest priority which is Highest priority which is allocated allocated to processes requiring a to processes requiring a very fast very fast response.response.

•• Clock level priority.Clock level priority. Allocated to periodic Allocated to periodic processes.processes.

•• Within these, further levels of priority may beWithin these, further levels of priority may be assignedassigned..

Dr. D. M. Akbar Hussain

Department of Electronic Systems 42

Within these, further levels of priority may be Within these, further levels of priority may be assignedassigned..

©Ian Sommerville

Page 22: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 22

Interrupt Interrupt ServicingServicing

•• Control is transferred Control is transferred automaticallyautomatically to a to a prepre--determined determined memory locationmemory location..

•• This location contains an instruction This location contains an instruction to jump to to jump to an an interrupt service interrupt service routine (ISR).routine (ISR).

•• Further interrupts are disabled, Further interrupts are disabled, the interrupt the interrupt serviced serviced and control returned to the and control returned to the interrupted interrupted process.process.

Dr. D. M. Akbar Hussain

Department of Electronic Systems 43

•• Interrupt service routines Interrupt service routines MUST be shortMUST be short, , simple simple and fast.and fast.

©Ian Sommerville

Periodic Periodic Process Process SServicingervicing

•• InIn mostmost realreal--timetime systems,systems, therethere willwill bebe severalseveral classesclasses ofof periodicperiodic process,process, eacheachwithwith differentdifferent periodsperiods (the(the timetime betweenbetween executions),executions), executionexecution timestimes andanddeadlinesdeadlines (the(the timetime byby whichwhich processingprocessing mustmust bebe completedcompleted))..

•• TheThe processprocess managermanager selectsselects aa processprocess whichwhich isis readyready forfor executionexecution..

Dr. D. M. Akbar Hussain

Department of Electronic Systems 44©Ian Sommerville

Page 23: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 23

Process Process ManagementManagement

•• Concerned with managing the set of concurrent processesConcerned with managing the set of concurrent processes..g g pg g p

•• Periodic processes are executed at prePeriodic processes are executed at pre--specified time intervalsspecified time intervals..

•• The RTOS uses the realThe RTOS uses the real--time clock to determine when to execute time clock to determine when to execute a process a process taking into accounttaking into account::

–– Process period Process period -- Time Time between executions.between executions.–– Process deadline Process deadline -- The The time by which processing must be complete.time by which processing must be complete.

Dr. D. M. Akbar Hussain

Department of Electronic Systems 45

y p g py p g p

©Ian Sommerville

RTE RTE Process Process MManagementanagement

Resource Manager

Allocate memoryand processor

Scheduler

Choose processfor execution

Despatcher

Start Execution on anavailable processor

Dr. D. M. Akbar Hussain

Department of Electronic Systems 46©Ian Sommerville

Page 24: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 24

Process Process SwitchingSwitching

•• The scheduler chooses the The scheduler chooses the next process next process to be executed by the processor. to be executed by the processor.

•• This This depends on a scheduling strategy which may take the depends on a scheduling strategy which may take the process priority process priority into accountinto account..

•• The resource manager The resource manager allocates memory and a processor allocates memory and a processor for the process for the process to be executedto be executed..

Dr. D. M. Akbar Hussain

Department of Electronic Systems 47

•• The dispatcher takes the process The dispatcher takes the process from ready list, loads it from ready list, loads it onto a processor onto a processor and starts execution.and starts execution.

©Ian Sommerville

Scheduling Scheduling StrategiesStrategies

•• Non preNon pre--emptive schedulingemptive scheduling–– Once a process has been scheduled for execution, it runs to completion or Once a process has been scheduled for execution, it runs to completion or

until it is blocked for some reason (e.g. waiting for I/Ountil it is blocked for some reason (e.g. waiting for I/O).).

•• PrePre--emptive schedulingemptive scheduling–– The execution of an executing processes may be stopped if a higher priority The execution of an executing processes may be stopped if a higher priority

process requires serviceprocess requires service..

•• Scheduling Scheduling algorithmsalgorithms

Dr. D. M. Akbar Hussain

Department of Electronic Systems 48

–– RoundRound--robin.robin.–– Rate Rate monotonic.monotonic.–– Shortest deadline first.Shortest deadline first.

©Ian Sommerville

Page 25: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 25

Monitoring and Monitoring and Control Control SSystemsystems

•• ImportantImportant classclass ofof realreal--timetime systems,systems, continuouslycontinuously checkcheck sensorssensors andandtaketake actionsactions dependingdepending onon sensorsensor valuesvalues..

•• MonitoringMonitoring systemssystems examineexamine sensorssensors andand reportreport theirtheir resultsresults..

•• ControlControl systemssystems taketake sensorsensor valuesvalues andand controlscontrols thethe ActuatorActuator HardwareHardware..

Dr. D. M. Akbar Hussain

Department of Electronic Systems 49©Ian Sommerville

Generic Generic ArchitectureArchitecture

Testingprocess

S1

S2

S3

P (S1)

P (S2)

P (S3)

Monitoringprocesses

Controlprocesses

P (A1)

P (A2)

P (A3)

A1

A2

A3

process

Dr. D. M. Akbar Hussain

Department of Electronic Systems 50

P (A4) A4

Control panelprocesses

©Ian Sommerville

Page 26: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 26

Burglar Burglar Alarm Alarm SSystemystem

•• A system is required to monitor sensors on doors and windows to A system is required to monitor sensors on doors and windows to detect the presence of intruders in a buildingdetect the presence of intruders in a building..

•• When a sensor indicates a breakWhen a sensor indicates a break--in, the system switches on lights in, the system switches on lights around the area and calls police automaticallyaround the area and calls police automatically..

•• The system should include provision for operation without a mains The system should include provision for operation without a mains

Dr. D. M. Akbar Hussain

Department of Electronic Systems 51

y p py p ppower supply.power supply.

©Ian Sommerville

Burglar Burglar Alarm SystemAlarm System

•• SensorsSensors–– Movement detectors, window sensors, door sensors;Movement detectors, window sensors, door sensors;–– 50 window sensors, 30 door sensors and 200 movement 50 window sensors, 30 door sensors and 200 movement detectorsdetectors;;–– Voltage drop sensorVoltage drop sensor..

•• ActionsActions–– When an intruder is detected, police are called When an intruder is detected, police are called automaticallyautomatically;;–– Lights are switched on in rooms with active sensors;Lights are switched on in rooms with active sensors;–– An audible alarm is switched on;An audible alarm is switched on;

Th t it h t ti ll t b k h lt d iTh t it h t ti ll t b k h lt d i

Dr. D. M. Akbar Hussain

Department of Electronic Systems 52

–– The system switches automatically to backup power when a voltage drop is The system switches automatically to backup power when a voltage drop is detected.detected.

©Ian Sommerville

Page 27: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 27

The RThe R--T T System System DDesign esign PProcessrocess

•• IdentifyIdentify stimulistimuli andand associatedassociated responsesresponses•• IdentifyIdentify stimulistimuli andand associatedassociated responsesresponses..

•• DefineDefine thethe timingtiming constraintsconstraints associatedassociated withwith eacheach stimulusstimulus andand responseresponse..

•• AllocateAllocate systemsystem functionsfunctions toto concurrentconcurrent processesprocesses..

•• DesignDesign algorithmsalgorithms forfor stimulusstimulus processingprocessing andand responseresponse generationgeneration..

D iD i h d lih d li tt hi hhi h th tth t illill ll bb

Dr. D. M. Akbar Hussain

Department of Electronic Systems 53

•• DesignDesign aa schedulingscheduling systemsystem whichwhich ensuresensures thatthat processesprocesses willwill alwaysalways bebescheduledscheduled toto meetmeet theirtheir deadlinesdeadlines..

©Ian Sommerville

Stimuli to be Stimuli to be ProcessedProcessed

•• Power Power FailureFailure–– Generated Generated aa--periodically periodically by a circuit monitor. When received, the system by a circuit monitor. When received, the system

must switch to backup power within 50 msmust switch to backup power within 50 ms..

•• Intruder Intruder AlarmAlarm–– Stimulus generated by system sensors. Response is to call the police, switch Stimulus generated by system sensors. Response is to call the police, switch

on building lights and the audible alarm.on building lights and the audible alarm.

Dr. D. M. Akbar Hussain

Department of Electronic Systems 54©Ian Sommerville

Page 28: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 28

Timing Timing RequirementsRequirements

Stimulus/Response Timing requirementsPower fail interrupt The switch to backup power must be completedPower fail interrupt The switch to backup power must be completed

within a deadline of 50 ms. Door alarm Each door alarm should be polled twice per

second.Window alarm Each window alarm should be polled twice per

second.Movement detector Each movement detector should be polled twice

per second.Audible alarm The audible alarm should be switched on within

1/2 second of an alarm being raised by a sensor. Li ht it h Th li ht h ld b it h d ithi 1/2

Dr. D. M. Akbar Hussain

Department of Electronic Systems 55

Lights switch The lights should be switched on within 1/2 second of an alarm being raised by a sensor.

Communications The call to the police should be started within 2 seconds of an alarm being raised by a sensor.

Voice synthesiser A synthesised message should be available within 4 seconds of an alarm being raised by a sensor.

©Ian Sommerville

Burglar Burglar Alarm Alarm SSystem ystem PProcessesrocesses

Dr. D. M. Akbar Hussain

Department of Electronic Systems 56©Ian Sommerville

Page 29: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 29

Building_monitorBuilding_monitor process 1 process 1

class BuildingMonitor extends Thread {

BuildingSensor win door move ;BuildingSensor win, door, move ;

Siren siren = new Siren () ;Lights lights = new Lights () ;Synthesizer synthesizer = new Synthesizer () ;DoorSensors doors = new DoorSensors (30) ;WindowSensors windows = new WindowSensors (50) ;MovementSensors movements = new MovementSensors (200) ;PowerMonitor pm = new PowerMonitor () ;

BuildingMonitor()

Dr. D. M. Akbar Hussain

Department of Electronic Systems 57

{// initialise all the sensors and start the processessiren.start () ; lights.start () ;synthesizer.start () ; windows.start () ;doors.start () ; movements.start () ; pm.start () ;

}

©Ian Sommerville

Building monitor process 2Building monitor process 2public void run ()

{int room = 0 ;while (true)while (true){

// poll the movement sensors at least twice per second (400 Hz)move = movements.getVal () ;// poll the window sensors at least twice/second (100 Hz)win = windows.getVal () ;// poll the door sensors at least twice per second (60 Hz)door = doors.getVal () ;if (move.sensorVal == 1 | door.sensorVal == 1 | win.sensorVal == 1)

{// a sensor has indicated an intruder

Dr. D. M. Akbar Hussain

Department of Electronic Systems 58

if (move.sensorVal == 1) room = move.room ;if (door.sensorVal == 1) room = door.room ;if (win.sensorVal == 1 ) room = win.room ;

lights.on (room) ; siren.on () ; synthesizer.on (room) ;break ;

}}

©Ian Sommerville

Page 30: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 30

Building_monitorBuilding_monitor process 3 process 3

lights.shutdown () ; siren.shutdown () ; synthesizer.shutdown () ;windows.shutdown () ; doors.shutdown () ; movements.shutdown () ;

} // run} //BuildingMonitor

Dr. D. M. Akbar Hussain

Department of Electronic Systems 59©Ian Sommerville

Control Control SystemsSystems

•• AA burglarburglar alarmalarm systemsystem isis primarilyprimarily aa monitoringmonitoring systemsystem.. ItIt collectscollects datadatafromfrom sensorssensors butbut nono realreal--timetime actuatoractuator controlcontrol..

•• ControlControl systemssystems areare similarsimilar but,but, inin responseresponse toto sensorsensor values,values, thethesystemsystem sendssends controlcontrol signalssignals toto actuatorsactuators..

•• AnAn exampleexample ofof aa monitoringmonitoring andand controlcontrol systemsystem isis aa systemsystem thatthatmonitorsmonitors temperaturetemperature andand switchesswitches heatersheaters onon andand offoff..

Dr. D. M. Akbar Hussain

Department of Electronic Systems 60©Ian Sommerville

Page 31: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 31

A A Temperature Temperature CControl Systemontrol System

500 Hz

Thermostatprocess

Sensorprocess

500 HzSensorvalues

Dr. D. M. Akbar Hussain

Department of Electronic Systems 61

Furnacecontrol process

Heater contr olprocess

Thermostat process500 HzSwitch commandRoom Number

©Ian Sommerville

Data Data Acquisition Acquisition SSystemsystems

•• CollectCollect datadata fromfrom sensorssensors forfor subsequentsubsequent processingprocessing andand analysisanalysis..

•• DataData collectioncollection processesprocesses andand processingprocessing processesprocesses maymay havehave differentdifferent periodsperiodsandand deadlinesdeadlines..

•• DataData collectioncollection maymay bebe fasterfaster thanthan processingprocessing ee..gg.. collectingcollecting informationinformation aboutabout ananexplosionexplosion..

Dr. D. M. Akbar Hussain

Department of Electronic Systems 62

•• CircularCircular oror ringring buffersbuffers areare aa mechanismmechanism forfor smoothingsmoothing speedspeed differencesdifferences..

©Ian Sommerville

Page 32: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 32

Data Data Acquisition Acquisition AArchitecturerchitecture

S

Sensors (each data flow is a sensor value)Sensor

DisplayProcessdata

Sensor databuffer

Sensorprocess

Sensoridentifier and

value

Sensoridentifier and

value

Sensorid tifi d

Sensoridentifier and

s1

s2

s3

s4

Dr. D. M. Akbar Hussain

Department of Electronic Systems 63

Processdata

Sensor databuffer

Sensorprocess

identifier andvalue

identifier andvalue

s

s5

s6

©Ian Sommerville

Reactor Reactor Data Data CCollectionollection

•• AA systemsystem collectscollects datadata fromfrom aa setset ofof sensorssensors monitoringmonitoring thethe neutronneutron fluxfluxfromfrom aa nuclearnuclear reactorreactor..

•• FluxFlux datadata isis placedplaced inin aa ringring bufferbuffer forfor laterlater processingprocessing..

•• TheThe ringring bufferbuffer isis itselfitself implementedimplemented asas aa concurrentconcurrent processprocess soso thatthat thethecollectioncollection andand processingprocessing processesprocesses maymay bebe synchronizedsynchronized

Dr. D. M. Akbar Hussain

Department of Electronic Systems 64

collectioncollection andand processingprocessing processesprocesses maymay bebe synchronizedsynchronized..

©Ian Sommerville

Page 33: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 33

Reactor Reactor Flux MonitoringFlux Monitoring

Operatordisplay

Fluxprocessing

Flux databuffer

A-Dconvertor

Sensoridentifier and

flux valueProcessedFlux Level

Neutron flux sensors

Dr. D. M. Akbar Hussain

Department of Electronic Systems 65©Ian Sommerville

A RA Ring Buffering Buffer

Dr. D. M. Akbar Hussain

Department of Electronic Systems 66©Ian Sommerville

Page 34: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 34

Mutual Mutual ExclusionExclusion

•• ProducerProducer processesprocesses collectcollect datadata andand addadd itit toto thethe bufferbuffer.. ConsumerConsumer processesprocessestaketake datadata fromfrom thethe bufferbuffer andand makemake elementselements availableavailable..

•• ProducerProducer andand consumerconsumer processesprocesses mustmust bebe mutuallymutually excludedexcluded fromfrom accessingaccessing thethesamesame elementelement..

•• TheThe bufferbuffer mustmust stopstop producerproducer processesprocesses addingadding informationinformation toto aa fullfull bufferbuffer andandconsumerconsumer processesprocesses tryingtrying toto taketake informationinformation fromfrom anan emptyempty bufferbuffer..

Dr. D. M. Akbar Hussain

Department of Electronic Systems 67©Ian Sommerville

Ring Ring Buffer Buffer IImplementation mplementation 11

class CircularBuffer {{

int bufsize ;SensorRecord [] store ;int numberOfEntries = 0 ;int front = 0, back = 0 ;

CircularBuffer (int n) {

Dr. D. M. Akbar Hussain

Department of Electronic Systems 68

CircularBuffer (int n) {bufsize = n ;store = new SensorRecord [bufsize] ;

} // CircularBuffer

©Ian Sommerville

Page 35: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 35

Ring Ring Buffer Buffer IImplementation mplementation 22

synchronized void put (SensorRecord rec )synchronized void put (SensorRecord rec ) throws InterruptedException

{if ( numberOfEntries == bufsize)

wait () ;store [back] = new SensorRecord (rec.sensorId, rec.sensorVal) ;back = back + 1 ;if (back == bufsize)

back = 0 ;

Dr. D. M. Akbar Hussain

Department of Electronic Systems 69

;numberOfEntries = numberOfEntries + 1 ;notify () ;

} // put

©Ian Sommerville

Ring Ring Buffer Implementation Buffer Implementation 33

synchronized SensorRecord get () throws InterruptedException {{

SensorRecord result = new SensorRecord (-1, -1) ;if (numberOfEntries == 0)

wait () ;result = store [front] ;front = front + 1 ;if (front == bufsize)

front = 0 ;b OfE t i b OfE t i 1

Dr. D. M. Akbar Hussain

Department of Electronic Systems 70

numberOfEntries = numberOfEntries - 1 ;notify () ;return result ;

} // get} // CircularBuffer

©Ian Sommerville

Page 36: Course Teacher: D. M. Akbar Hussain - Aalborg Universitethomes.et.aau.dk/akh/2011/real-time-ep-2011_files/lect2-1-RTES-Clas… · DE5 Thursday, September 23, 2010 Real-time Embedded

DE5 Thursday, September 23, 2010

Real-time Embedded System Programming 36

Key pointsKey points

1.1. RealReal--timetime systemsystem correctnesscorrectness dependsdepends notnot justjust onon whatwhat thethe systemsystem doesdoes butbut alsoalsoonon howhow fastfast itit reactsreacts..

2.2. AA generalgeneral RTRT systemsystem modelmodel involvesinvolves associatingassociating processesprocesses withwith sensorssensors andandactuatorsactuators..

3.3. RealReal--timetime systemssystems architecturesarchitectures areare usuallyusually designeddesigned asas aa numbernumber ofof concurrentconcurrentprocessesprocesses..

4.4. RealReal--timetime operatingoperating systemssystems areare responsibleresponsible forfor processprocess andand resourceresourcemanagementmanagement

Dr. D. M. Akbar Hussain

Department of Electronic Systems 71

managementmanagement..

5.5. MonitoringMonitoring andand controlcontrol systemssystems pollpoll sensorssensors andand sendsend controlcontrol signalsignal toto actuatorsactuators..

6.6. DataData acquisitionacquisition systemssystems areare usuallyusually organisedorganised accordingaccording toto aa producerproducer consumerconsumermodelmodel..

©Ian Sommerville