+ All Categories
Home > Documents > Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming...

Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming...

Date post: 19-Dec-2015
Category:
View: 229 times
Download: 3 times
Share this document with a friend
Popular Tags:
75
Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions
Transcript
Page 1: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings

Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings

Chapter 10: Programming Real-Time Abstractions

Page 2: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 2 of 75

Aim Show how languages support the

programming of real-time abstractions Periodic activities Sporadic activities Jitter control

Page 3: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 3 of 75

Real-Time Threads in the RTSJ Unlike Ada, Real-Time Java explicitly distinguishes

between threads and real-time threads. Real-time threads have the following attributes:

Release parameters Scheduling parameters Memory parameters Processing group parameters

Page 4: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 4 of 75

Release Parameters The processing cost for each release and its

blocking time Its deadline If the object is periodic or sporadic then an

interval is also given Event handlers can be specified for the situation

where the deadline is missed or the processing resource consumed is greater than the cost specified

There is no requirement to monitor the processing time consumed by a schedulable object

Page 5: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 5 of 75

ReleaseParameters Class

public class ReleaseParameters implements Cloneable{

protected ReleaseParameters(RelativeTime cost, RelativeTime deadline, RelativeTime blockingTerm, AsyncEventHandler overrunHandler, AsyncEventHandler missHandler); ... // methods public RelativeTime getCost(); public void setCost(RelativeTime cost); ...}

Page 6: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 6 of 75

Scheduling Parameters An empty class Subclasses allow the priority of the object to

be specified and, potentially, its importance to the overall functioning of the application

Although the RTSJ specifies a minimum range of real-time priorities (28), it makes no statement on the allowed values of the importance parameter

Page 7: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 7 of 75

Other parameters MemoryParameters

the maximum amount of memory used by the object in an associated memory area

the maximum amount of memory used in immortal memory a maximum allocation rate of heap memory.

ProcessingGroupParameters

allows several schedulable objects to be treated as a group and to have an associated period, cost and deadline

Page 8: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 8 of 75

An extract from the RealtimeThread Class

package javax.realtime;public class RealtimeThread extends java.lang.Thread implements Schedulable { public RealtimeThread(); public RealtimeThread(SchedulingParameters scheduling, ReleaseParameters release); public RealtimeThread(SchedulingParameters scheduling, ReleaseParameters release, MemoryParameters memory, MemoryArea area, ProcessingGroupParameters group, Runnable logic); ... public void start(); public void release();

public static boolean waitForNextPeriod(); public static boolean waitForNextRelease(); // note there are AIE interruptible versions of the above ...}

Page 9: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 9 of 75

task body Periodic_T is Next_Release : Time; Release_Interval : Time_Span := Milliseconds(...);begin -- read clock and calculate the next -- release time (Next_Release) loop -- sample data (for example) or -- calculate and send a control signal delay until Next_Release; Next_Release := Next_Release + Release_Interval; end loop;end Periodic_T;

Periodic Tasks - Ada

Page 10: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 10 of 75

Periodic Task - POSIX Similar structure to Ada Uses clock_nanosleep which is like delay until in Ada

The parameter remaining_time indicates how much time left if thread signals ‘while asleep’

Page 11: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 11 of 75

Code

#include <signal.h>#include <time.h>#include <pthread.h>#include <misc/timespec_operations.h>void periodic_thread() /* destined to be the thread */{ struct timespec next_release, remaining_time; struct timespec thread_period; /* actual period */

/* read clock and calculate the next release time (next_release) */

Page 12: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 12 of 75

Codewhile(1) { /* sample data (for example) or calculate and send a control signal */ clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &next_release, &remaining_time); add_timespec(&next_release, &next_release, &thread_period); }}

int init(){ pthread_attr_t attributes; /* thread attributes */ pthread_t PT; /* thread pointer */

pthread_attr_init(&attributes); /* default attributes */ pthread_create(&PT, &attributes, (void *)periodic_thread, (void *)0);}

Page 13: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 13 of 75

Periodic Task – Real-Time Java Represented by a real-time thread with associated

periodic release parameters and start time relative, or absolute

Page 14: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 14 of 75

PeriodicParameters classpublic class PeriodicParameters extends ReleaseParameters { ... public PeriodicParameters( HighResolutionTime start, RelativeTime period, RelativeTime cost, RelativeTime deadline, RelativeTime blockingTerm, AsyncEventHandler overrunHandler, AsyncEventHandler missHandler);

// methods public RelativeTime getPeriod(); public HighResolutionTime getStart(); public void setPeriod(RelativeTime period); public void setStart(HighResolutionTime start);}

Page 15: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 15 of 75

A Simple Model of Periodic Threads

public class Periodic extends RealtimeThread{ public Periodic(PeriodicParameters P) { ... };

public void run() { boolean deadlineMet= true; while(deadlineMe) { // code to be run each period ... deadlineMet = waitForNextPeriod(); } // a deadline has been missed, // and there is no handler ... }}

Page 16: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 16 of 75

Defining a periodic thread Loop required but not the explicit calculation of delay So for period 10ms, deadline 5ms, 1ms execution

time, starting at absolute time A:{ AbsoluteTime A = new AbsoluteTime(...); PeriodicParameters P = new PeriodicParameters( A, // start time new RelativeTime(10,0), // period new RelativeTime(1,0), // cost new RelativeTime(5,0), // deadline null, null ); // no deadline miss/cost overrun handlers

Periodic ourThread = new Periodic(P); //create thread ourThread.start(); // release it}

Page 17: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 17 of 75

Semantics of waitForNextPeriod

Complex, here just the main points given. On a DEADLINE MISS

If there are no handlers, waitForNextPeriod (wFNP) will not block the thread in the event of a deadline miss (if returns false immediately) . The RTSJ assumes that in this situation the thread itself will undertake some corrective action

Where the handler is available, the RTSJ assumes that the handler will take some corrective action and therefore it automatically deschedules the thread

(if appropriate) the handler reschedule the thread If deadline met

wFNP returns true at the next release time

Page 18: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 18 of 75

Aperiodic and Sporadic Activities

Non-periodic activities are classified as either sporadic if there is a minimum inter-arrival time (MIT), otherwise aperiodic.

Page 19: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 19 of 75

Aperiodics in Ada

protected Aperiodic_Controller is procedure Interrupt; entry Wait_For_Next_Interrupt; -- requires pragmas to define the procedure -- to be an interruptprivate Call_Outstanding : Boolean := False;end Aperiodic_Controller;

Page 20: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 20 of 75

Aperiodics in Adaprotected body Aperiodic_Controller is procedure Interrupt is begin Call_Outstanding := True; end Interrupt;

entry Wait_For_Next_Interrupt when Call_Outstanding is begin Call_Outstanding := False; end Wait_For_Next_Interrupt;end Aperiodic_Controller;

Page 21: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 21 of 75

Client task

task body Aperiodic_T isbegin loop Aperiodic_Controller. Wait_For_Next_Interrupt; -- action end loop;end Aperiodic_T;

Page 22: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 22 of 75

Tasks and Events Two forms of computation

Tasks – long lived with state, they repeat Events – one-off, no state

Events are said to be triggered, or fired, invoked, or delivered

Interrupts are events Timing events happen when a defined

clock reaches a specified value

Page 23: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 23 of 75

Timing Events in Ada A means of defining code that is

executed at a future point in time Does not need a task Similar in notion to interrupt handing

(time itself generates the interrupt) Again a handler is used

Page 24: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 24 of 75

Timing Events (cont’d)package Ada.Real_Time.Timing_Events is type Timing_Event is tagged limited private; type Timing_Event_Handler is access protected procedure(Event : in out Timing_Event);

procedure Set_Handler(Event : in out Timing_Event; At_Time : Time; Handler: Timing_Event_Handler);

procedure Set_Handler(Event : in out Timing_Event; In_Time: Time_Span; Handler: Timing_Event_Handler);

Page 25: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 25 of 75

Timing Events (cont’d) function Is_Handler_Set(Event : Timing_Event) return Boolean;

function Current_Handler(Event : Timing_Event) return Timing_Event_Handler;

procedure Cancel_Handler(Event : in out Timing_Event; Cancelled : out Boolean);

function Time_Of_Event(Event : Timing_Event) return Time;private ... -- Not specified by the language.end Ada.Real_Time.Timing_Events;

Page 26: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 26 of 75

Time-triggered in POSIX Via signals generated from timers One-shot and period timers can be

created Can be associated with any clock

Page 27: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 27 of 75

POSIX interface to timers#define TIMER_ABSTIME ..

struct itimerspec { struct timespec it_value; /* first timer signal */ struct timespec it_interval; /* subsequent intervals */};typedef ... timer_t;

int timer_create(clockid_t clock_id, struct sigevent *evp, timer_t *timerid); /* Create a per-process timer using the specified clock as */ /* the timing base. evp points to a structure which contains */ /* all the information needed concerning the signal */ /* to be generated. */

Page 28: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 28 of 75

POSIX interface to timersint timer_delete(timer_t timerid); /* delete a per-process timer */

int timer_settime(timer_t timerid, int flags, const struct itimerspec *value, struct itimerspec *ovalue); /* Set the next expiry time for the timer specified. */ /* If flags is set to TIMER_ABSTIME, then */ /* the timer will expire when the clock reaches the /* absolute value specified by *value.it_value */ /* if flags is NOT set to TIMER_ABSTIME, then the timer will */ /* expire when the interval specified by value.it_value passes */ /* if *value.it_interval is non-zero, then a periodic timer */ /* will go off every value->it_interval after */ /* value->it_value has expired */ /* Any previous timer setting is returned in *ovalue */

Page 29: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 29 of 75

POSIX interface to timers

int timer_gettime(timer_t timerid, struct itimerspec *value); /* get the details of the current timer */

int timer_getoverrun(timer_t timerid); /* if real-time signals are supported, * / /* return the number of signals */ /* that have been generated by this timer but not handled */

/* All the above functions, except timer_getoverrun, return 0 *//* if successful, otherwise -1. timer_getoverrun returns the *//* number of overruns. When an error condition is returned *//* by any of the above functions, a shared variable errno *//* contains the reason for the error */

Page 30: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 30 of 75

Aperiodic and Sporadic In Java

Aperiodics considered here Sporadics deferred

Page 31: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 31 of 75

Aperiodic Parameterspublic class AperiodicParameters extends ReleaseParameters { public static final String arrivalTimeQueueOverflowExcept; public static final String arrivalTimeQueueOverflowIgnore; public static final String arrivalTimeQueueOverflowReplace; public static final String arrivalTimeQueueOverflowSave;

// constructors not shown

public String getArrivalTimeQueueOverflowBehavior(); public void setArrivalTimeQueueOverflowBehavior( String behavior); ...}

Page 32: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 32 of 75

A Simple Model of Aperiodic Threads

public class Aperiodic extends RealtimeThread{ public Periodic(PeriodicParameters P) { ... };

public void run() { boolean deadlineMet= true; while(deadlineMe) { // code to be run each period ... deadlineMet = waitForNextRelease(); } // a deadline has been missed, // and there is no handler ... }}

Page 33: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 33 of 75

Time Triggered Events in Real-Time Java

Unlike Ada, the handlers are scheduled The abstract Timer class defines the base class from which timer

events can be generated All timers are based on a clock; a null clock values indicates that

the RealtimeClock should be used A timer has a time at which it should fire; that is release its

associated handlers This time may be an absolute or relative time value If no handlers have been associated with the timer, nothing will

happen when the timer fires

Page 34: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 34 of 75

Timer package javax.realtime;public abstract class Timer extends AsyncEvent { // constructors protected Timer(HighResolutionTime time, Clock clock, AsyncEventHandler handler);

// methods public ReleaseParameters createReleaseParameters(); public void destroy(); public void disable(); public void enable(); public Clock getClock(); public AbsoluteTime getFireTime(); public void reschedule(HighResolutionTime time); public void start(); public boolean stop();}

Page 35: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 35 of 75

Timers II Once created a timer can be explicitly destroyed, disabled (which

allows the timer to continue counting down but prevents it from firing) and enabled (after it has been disabled)

If a timer is enabled after its firing time has passed, the firing is lost

The reschedule method allows the firing time to be changed Finally the start method, starts the timer going Any relative time given in the constructor is converted to an

absolute time at this point; if an absolute time was given in the constructor, and the time has passed, the timer fires immediately

Page 36: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 36 of 75

One Shot Timer

package javax.realtime;public class OneShotTimer extends Timer{ // constructors public OneShotTimer(HighResolutionTime fireTime, AsyncEventHandler handler); // assumes the default real-time clock

public OneShotTimer(HighResolutionTime fireTime, Clock clock, AsyncEventHandler handler); // fireTime is based on the clock parameter}

Page 37: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 37 of 75

Periodic Timerpackage javax.realtime;public class PeriodicTimer extends Timer { // constructors public PeriodicTimer(HighResolutionTime start, RelativeTime interval, AsyncEventHandler handler); public PeriodicTimer(HighResolutionTime start, RelativeTime interval, Clock clock, AsyncEventHandler handler);

// methods public ReleaseParameters createReleaseParameters(); public void fire(); // deprecated public AbsoluteTime getFireTime(); public RelativeTime getInterval(); public void setInterval(RelativeTime interval);}

Page 38: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 38 of 75

Controlling I/O Jitter A periodic control task needs to take

input from the environment is a very regular way, and similarly produce output with little variation in time Input jitter Output jitter

Page 39: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 39 of 75

Controlling Input and Output Jitter

Sensors and actuators are read and written by asynchronous event handlers

Work done by a task

Processing real-time thread

0 Max InputJitter

MinimumLatency

Deadline(Max latency)

Page 40: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 40 of 75

Controlling jitter in Ada Use a timing event for input and a

separate timing event for output Use a task for processing the input data

to produce the output Assume a period of 40ms in a controller

Page 41: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 41 of 75

Sensor Reader spec

protected type Sensor_Reader is pragma Interrupt_Priority (Interrupt_Priority’Last); procedure Start; entry Read(Data : out Sensor_Data); procedure Timer(Event : in out Timing_Event);end Sensor_Reader;

Input_Jitter_Control : Timing_Event;Input_Period : Time_Span := Milliseconds(40);

Page 42: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 42 of 75

Sensor Reader bodyprotected body Sensor_Reader is procedure Start is begin Reading := Read_Sensor; Next_Time := Clock + Input_Period; Data_Available := True; Set_Handler(Input_Jitter_Control, Next_Time, Timer'Access); end Start;

entry Read(Data : out Sensor_Data) when Data_Available is begin Data := Reading; Data_Available := False; end Read;

Page 43: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 43 of 75

Sensor Reader body

procedure Timer(Event : in out Timing_Event) is begin -- Reading from sensor interface Data_Available := True; Next_Time := Next_Time + Input_Period; Set_Handler(Input_Jitter_Control, Next_Time, Timer'Access); end Timer;

end Sensor_Reader;

Page 44: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 44 of 75

Output jitter control A type is also defined for output jitter

control (Actuator_Writer) Assuming a deadline of 30ms (period is

40ms) and max output jitter of 4ms:

SR.start; -- of type Sensor_Readerdelay 0.026; -- ie 26ms laterAW.start; -- of type Actuator_Writer

Page 45: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 45 of 75

Controlling task

task type Control_Algorithm (Input : access Sensor_Reader; Output : access Actuator_Writer);task body Control_Algorithm is Input_Data : Sensor_Data; Output_Data : Actuator_Data;begin loop Input.Read(Input_Data); -- process data; Output.Write(Output_Data); end loop;end Control_Algorithm;

Page 46: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 46 of 75

Controlling jitter in POSIX Uses timers and threads Following example used three threads

with offset release times

Page 47: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 47 of 75

Three Thread Solution

Input thread

Outputthread

Processing thread

0 Max InputJitter

MinimumLatency

Deadline(Max latency)

Page 48: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 48 of 75

POSIX codetypedef struct { struct timespec start; struct timespec period; struct timespec max_input_jitter; struct timespec min_latency; struct timespec deadline;} parameters;void sensor_thread(parameters *params) /* destined to be the thread that reads the sensor*/{ struct timespec next_release, remaining_time; /* wait until start time */ next_release = params->start; clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &next_release, &remaining_time);

Page 49: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 49 of 75

POSIX codewhile(1) { /* read sensor data and store in a global data - protected by a mutex */ add_timespec(&next_release, &next_release, &params->period);

clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &next_release, &remaining_time); }}

Page 50: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 50 of 75

POSIX codevoid processing_thread(parameters *params)/* destined to be the thread thatprocesses the sensor data*/

{ struct timespec next_release, remaining_time;

/* wait until first release time */ add_timespec(&next_release, &(params->start), &(params->max_input_jitter)); clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &next_release, &remaining_time);

Page 51: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 51 of 75

POSIX codewhile(1) { /* get data written by input_thread, process data and write the value to be written to the actuator in global data - protected by a mutex */ add_timespec(&next_release, &next_release, &params->period); clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &next_release, &remaining_time); /* code to be executed each period here */ }}

Page 52: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 52 of 75

POSIX code

void actuator_thread(parameters *params) /* destined to be the thread that writes to the actuator */{ struct timespec next_release, remaining_time;

/* wait until first release time */ add_timespec(&next_release, &params->start, &params->min_latency);

clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &next_release, &remaining_time);

Page 53: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 53 of 75

POSIX code while(1) { /* get data written by processing_thread, process data and write the value to the actuator */

add_timespec(&next_release, &next_release, &params->period);

clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &next_release, &remaining_time); /* code to be executed each period here */ }}

Page 54: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 54 of 75

POSIX codevoid init(){

parameters P; struct timespec now; struct timespec init_time; int status; pthread_attr_t attributes_input; /* thread attributes */ pthread_t PTInput; /* thread pointer */ pthread_attr_init(&attribute_input); /* default attributes */ pthread_create(&PTInput, &attribute_input, (void *) sensor_thread, &P); // Similarly for the other threads }

Page 55: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 55 of 75

Controlling Input and Output Jitter

Sensors and actuators are read and written by asynchronous event handlers

The handlers can be given appropriate priorities and deadlines to ensure required jitter constraints are met.

Input ASEH

Output ASEH

Processing real-time thread

0 Max InputJitter

MinimumLatency

Deadline(Max latency)

Page 56: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 56 of 75

The Sensor Readerpublic class SensorReader extends AsyncEventHandler { public SensorReader() { super(); }

public void handleAsyncEvent() { Data = ...; synchronized(this) { dataAvailable = true; notifyAll(); } } public synchronized Data getData() throws InterruptedException { while(dataAvailable == false) wait(); dataAvailable = false return Data; ... } }

Page 57: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 57 of 75

The Control Processing Thread

public class ControlSystem extends RealtimeThread { public ControlSystem(SensorReader S, ActuatorWriter A) { super(); SR = S; AW = A; }

public void run() { while(true) { try { D = SR.getData(); // Process data AW.writeData(D); } catch (InterruptedException ie) {} } } private int D; private SensorReader SR; private ActuatorWriter AW;}

Page 58: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 58 of 75

The Main Programpublic class Main { public static void main (String [] args) { AbsoluteTime start = Clock.getRealtimeClock().getTime(); RelativeTime period = new RelativeTime(40,0); RelativeTime maxInputJitter = new RelativeTime(2,0); RelativeTime minLatency = new RelativeTime(26,0); SensorReader S = new SensorReader(); PeriodicTimer PT1 = new PeriodicTimer(start, period, S); start = start.add(minLatency); ActuatorWriter A = new ActuatorWriter(); PeriodicTimer PT2 = new PeriodicTimer( start, period, A); ControlSystem CS = new ControlSystem(S,A);

CS.start();PT1.start(); PT2.start(); }}

Page 59: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 59 of 75

Other Approaches to TS The following slides will consider other

approaches to supporting Temporal Scopes Euclid Pearl DSP Esterel Giotto

Page 60: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 60 of 75

Real-Time Euclid1. periodic frameInfo first activation timeOrEvent2. atEvent conditionId frameInfo The clause frameInfo defines the periodicity of the

process (including the maximum rate for sporadic processes).

The simplest form this can take is an expression in real-time units:frame realTimeExpn

The value of these units is set at the beginning of the program

Page 61: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 61 of 75

Periodic Process A periodic process can be activated for the first time by

having a start time defined waiting for an interrupt to occur waiting for either of above

The syntax for timeOrEvent must, therefore, be one of the followingatTime realTimeExpnatEvent conditionIdatTime realTimeExpn or atEvent conditionId

conditionId is a condition variable associated with an interrupt; it is also used with sporadic processes

Page 62: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 62 of 75

RT Euclid: Example A cyclic temperature controller with periodicity 60 units (every

minute if the time unit is set to 1 second) which become active after 600 units or when a startMonitoring interrupt arrives

realTimeUnit := 1.0 % time unit = 1 seconds

var Reactor: module % Euclid is module basedvar startMonitoring : activation condition atLocation 16#A10D% This defines a condition variable which is% mapped onto an interrupt

process TempController : periodic frame 60 first activation atTime 600 or atEvent startMonitoring % import list % % execution part % end TempControllerend Reactor

Note: no loop; scheduler controls the activation

Page 63: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 63 of 75

Pearl Provides explicit timing information concerning the

start, frequency and termination of processesEVERY 10 SEC ACTIVATE T

To activate at a particular point in time (say 12.00 noon each day):AT 12:00:00 ACTIVATE LUNCH

A sporadic task, S, released by an interrupt, IRT, is defined byWHEN IRT ACTIVATE S;

Page 64: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 64 of 75

Pearl or if an initial delay of one second is required:

WHEN IRT AFTER 1 SEC ACTIVATE S; A task in Pearl can be activated by a time schedule

or an interrupt but not both:AFTER 10 MIN ALL 60 SEC ACTIVATE

TempController;

WHEN startMonitoring ALL 60 SEC ACTIVATE TempController;

The term ALL 60 SEC means repeat periodically, after the first execution, every 60 seconds

Page 65: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 65 of 75

DPS Whereas Pearl, and RT Euclid have associate temporal

scopes with processes, and, therefore, necessitate the specification of timing constraints on the process itself, other languages such as DPS provide local timing facilities that apply at the block level

In general, a DPS temporal block (scope) may need to specify three distinct timing requirements (these are similar to the more global requirements discussed earlier): delay start by a known amount of time; complete execution by a known deadline; take no longer than a specified time to undertake a

computation

Page 66: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 66 of 75

DPS: Coffee Making Example

get_cupput_coffee_in_cupboil_waterput_water_in_cupdrink_coffeereplace_cup

Instant coffee

The act of making a cup of coffee should take no more than 10 minutes; drinking it is more complicated

A delay of 3 minutes should ensure that the mouth is not burnt

The cup itself should be emptied within 25 minutes (it would then be cold) or before 17:00 (that is, 5 o'clock and time to go home)

Page 67: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 67 of 75

DPS: Coffee Example Two temporal scopes are required:

start elapse 10 do get_cup put_coffee_in_cup boil_water put_water_in_cupend

start after 3 elapse 25 by 17:00 do drink_coffee replace_cupend

Page 68: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 68 of 75

DPS: Coffee Example For a temporal scope that is executed repetitively, a

time loop construct is useful:from <start> to <end> every <period>

For example, many software engineers require regular coffee throughout the working day:

from 9:00 to 16:15 every 45 do

make_and_drink_coffee

Page 69: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 69 of 75

EsterelSynchronous Hypothesis: Ideal systems produce their

outputs synchronously with their inputs Hence all computation and communication is assumed to take

zero time (all temporal scopes are executed instantaneously)module periodic;input tick;output result(integer);var V : integer in loop await 10 tick; -- undertake required computation to set V emit result(v); endend

A sporadic module has an identical form

Page 70: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 70 of 75

Esterel One consequence of the synchronous hypothesis is that

all actions are atomic This behaviour significantly reduces nondeterminism Unfortunately it also leads to potential causality problems

signal S in

present S else emit S end

end This program is incoherent: if S is absent then it is

emitted; on the other hand if it were present it would not be emitted

A formal definition of the behavioral semantics of Esterel helps to eliminate these problems

Page 71: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 71 of 75

Giotto A language for control applications Output produced at deadline, not before A task is logically executing from release

to deadline Example follows, note timing events can

be used to produce output Also hardware can be used to only

release output at the required time

Page 72: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 72 of 75

Example – pseudo code

sensor port temperature type integer range 10 .. 500 port pressure type integer range 0 .. 750actuator port heater type (on, off) port pump type integer 0 .. 9input T1 type integer range 10 .. 500 PI type integer range 0 .. 750output TO type (on, off) PO type integer 0 .. 9

Page 73: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 73 of 75

Example – pseudo codetask temperature input TI output TO temperature_controller taskpressure input PI output PO pressure_controller

driver temperature_sensor source temperature destination TI function read_temperaturedriver pressure_sensor source pressure destination PI function read_pressuredriver heater_actuator source TO destination heater function write_heaterdriver pump_actuator source PO destination pump function write_pump

mode normal period 20 ports TO, PO frequency 2 invoke temperature driver temperature_sensor frequency 1 invoke pressure driver pressure_sensor frequency 2 update heater_actuator frequency 1 update pump_actuatorstart normal

Page 74: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 74 of 75

Summary The right abstractions allow real-time

software to be produced efficiently But abstractions need to be the right

ones, and not hide key properties (eg temporal ones)

Ada and Java attempt to stay general purpose

Esterel, Giotto etc provide a more restricted computation model

Page 75: Real-Time Systems and Programming Languages © Alan Burns and Andy Wellings Chapter 10: Programming Real-Time Abstractions.

Real-Time Systems and Programming Languages: © Alan Burns and Andy Wellings 75 of 75

Summary Chapter has addressed the key

abstractions of Periodic tasks Sporadic and aperiodic tasks Jitter constrained tasks


Recommended