Real Time System and Programming Langauges

Embed Size (px)

Citation preview

  • 8/13/2019 Real Time System and Programming Langauges

    1/49

    REAL-TIME SYSTEMS AND

    PROGRAMMING LANGUAGES: 4th Edition

    Solutions to Selected Exercises

    A. Burns and A.J. WellingsDepartment of Computer Science, University of York, UK

    email burns,[email protected]

    May 2012

    Abstract

    This note gives examples of solutions to the exercises involving prob-lems in our book Real-Time Systems and Programming Languages: 4thEdition. Answers to questions involving more general discussion topics,or understanding of material presented in the chapters, are not given. Noguarantee is given that the questions or answers are correct or consistent .

    Question 2.3

    ensure Array_Is_Sortedby

    Bubble sortelse by

    Exchange sortelse

    error

    Question 2.5If an error is detected at P1 at time t, P1 is rolled back to recovery pointR13. No other processes are affected.

    If an error is detected at P2 at time t, P2 is rolled back to R23,unfortunately, it has communicated with P1, so P1 is rolled back to R12.

    If P3 detected error, it is rolled back to R32, this requires communi-cation with P2 and P4 to be undone; therefore P2 must be rolled backto R22 and P4 to R42. Rolling back P2 requires P1 to be rolled back toR12.

    1

  • 8/13/2019 Real Time System and Programming Langauges

    2/49

    If P4 detected error, it is rolled back to R43, this requires commu-nication with P3 to be undone; P3 is rolled back to R32. This requirescommunication with P2 and P4 to be undone; therefore P2 must be rolledback to R22. Rolling back P2 requires P1 to be rolled back to R12. Fi-nally, P4 must be rolled back again to R42.

    Question 3.21. any assertion check

    2. a watch dog timer detecting a missed deadline in another processes

    3. array bounds violation

    4. failure of a health monitoring check

    Question 3.3

    1 w i t h c ha r a c t e r_ i o ;2 p a ck a ge b od y l o o k i s3

    4 f unc t i on t e s t_c har ( c : c ha ra c t er )5 r e tu r n boo le a n i s6 begin7 - - r e tu r n s t r ue is va li d a l ph a

    8 - - n u me r i c c h a ra c te r e ls e f a ls e9 end;10

    11 f unc t i on r e a d r e t u rn punc t uat i on i s12 c : charac ter ;13 begin14 loop15 c : = c ha r a c t er _ i o .get ;16 i f t e s t_c har ( c ) / = t r ue t hen17 if c = . t he n18 charac ter_ io . f lush;19 r e tu r n pe r iod ;20 e nd i f ;21 if c = , t he n22 charac ter_ io . f lush;23 r e tu r n c om ma ;24 e nd i f ;25 if c = ; t he n26 charac ter_ io . f lush;27 r e turn semicolon ;28 e nd i f ;29 r a i se I LLEGAL_PUNCTUATI ON;30 e nd i f ;31 e nd l oop ;32 exception33 whe n I LLEGAL_PUNCTUATI ON = >34 charac ter_ io . f lush;35 r a i se ;36 - - o r r a is e I LLEGAL_PUNCTUATI ON 37 w h en I O_ E RR O R = >

    2

  • 8/13/2019 Real Time System and Programming Langauges

    3/49

    38 charac ter_ io . f lush;39 r a i se ;40 e nd r e a d ;41

    42 begin43 nul l ;44 end;

    1 w i t h l ook ;2 f unct i on ge t _punc t ua t i on r e t u rn punct ua ti on i s3 p : punc t uat i on ;4 begin5 loop6 begin7 p : = l o ok . r e ad ;8 ex i t ;9 exception

    10 w he n o t he r s = >11 nul l ;12 end;13 e nd l oop ;14 r e t ur n p ;15 e nd ge t _punc t ua t i on ;

    Question 3.4

    1 p r oce dur e r e l i a b le _he a t e r_o f f i s2 t ype s t age i s ( f i rs t , s ec ond , t h ir d , f ou rt h ) ;3 begin4

    5 f or i in s ta ge l oo p6 begin7 c as e i i s8 w he n f ir s t = >9 heater_off ;

    10 ex i t ;11 w he n s ec o nd = >12 i ncrease_coolant ;13 ex i t ;14 w he n t hi r d = >15 open_valve ;16 ex i t ;

    17 w he n f ou r th = >18 panic ;19 ex i t ;20 e nd c a se ;21 exception22 whe n he a t e r _ st uc k_on |23 t e m pe r a tu r e _s t il l _ r i s i ng |24 v a l ve _s tuc k = >25 nul l ;26 end;27 e nd l oop ;28 e nd r e l i a b le _he a t e r_o f f ;

    3

  • 8/13/2019 Real Time System and Programming Langauges

    4/49

    Question 3.8In the rst code fragment, the exception cannot be handled by the Do Somethingprocedure. The domain is the calling code.

    In the second code fragment, the exception can be handled by theDo Something procedure. The domain is the procedure.

    In the third code fragment, the exception can be handled within theinner block declared within the procedure. This block is the domain.

    Question 3.10All the alternatives will fail in the recovery block environment because thestate is restored have each has failed. Hence, the else clause is executed.

    In the exception handling environment, no state restoration occurs sothe secondary sets I to 20.

    Question 3.13The equivalent expression of the temperature control class would be:

    pub li c c l as s Va lve S tuc k e x t ends Exc ep t i on ;pub li c c l as s He a t e r St uc kOn e x t ends Exc ep t i on ;pub li c c l as s Te m pe r at u r e S t il l R i s i ng e x te nds Exc ep t i on ;

    pub li c c l as s Te m pe r at u r e Cont r o l{

    publ ic void hea terOn ( ) ;

    pub li c vo i d he a te r Off ( ) t h r ows He a t e r St uc kOn ;

    pub li c vo i d i nc r e a se Coo l a n t ()t h r ows Te m pe r at u r e S t i ll R i s i ng ;

    pub li c vo i d ope nVa l ve ( ) t h r ows Va l ve S t uc k ;

    pub li c vo i d pa n ic ( ) ;}

    And the turning the heater off reliably:

    pub li c s t a ti c vo i d r e l i a b le He a t e r Off ( ){

    Te m pe r at u r e Con tr o l TC = ne w Te m pe r at u r e Con tr o l ( ) ;b o ol e an d o ne = f al s e ;int I = 1;

    wh i le ( ! done ) {t ry {

    if (I == 1 ) {TC.he a te r Off ( ) ; done = t r ue ;

    } e ls e i f (I == 2 ) {TC. i nc r e a s eCoo l a n t ( ); done = t r ue ;

    } e ls e i f (I == 3 ) {

    4

  • 8/13/2019 Real Time System and Programming Langauges

    5/49

    TC.ope nVa l ve ( ) ; done = t r ue ;} e ls e {

    T C . p an i c () ; d o ne = t r ue ;Sys tem.out .pr in t ln("panic ca l l ed") ;

    }}c at ch ( E xc ep ti on E ) { I + +; }

    }}

    Question 3.14If an object is thrown which is not a subclass of Exception . It will notbe caught by the catch statement.

    Question 4.1

    1 w i t h Ada .Te x t_ I O; u s e Ada .Te x t _ IO;2 p r oce dur e M a i n i s3

    4 p r oce du re One i s5 begin6 d e l ay 1 .0 ;7 pu t _l i ne ( " one f i n is he d" ) ;8 e nd O ne ;9

    10

    11 p r oce du re Two i s12 begin13 d e l ay 2 .0 ;14 pu t _l i ne ( " t wo f i n is he d" ) ;15 e nd Two ;16

    17 p r oce du re Th r ee i s18 begin19 d e l ay 3 .0 ;20 pu t _l i ne ( " t h r ee f i n is he d" ) ;21 e nd Th r ee ;22

    23 t ype Po i n te r i s ac c e ss p r oc edu r e ;24

    25 t ype Pa r am e t er s is a r r ay ( Pos i t ive ra nge < > )26 o f Po i nt e r ;27

    28

    29 p r oce du re Run_Conc u r r e n t ly ( The s e : Pa ra m e te r s ) is30

    31 t a s k t ype Wor ke r ( Th i s : Po i nt e r ) ;32 t a sk b o dy Wo rk e r i s33 begin34 Thi s ;35 e nd Wor ke r ;36 t y pe Wo r ke r _ Po i nt e r i s a c ce s s Wor k er ;37 S t a rt e r : Wor ke r _Po i n t e r ;

    5

  • 8/13/2019 Real Time System and Programming Langauges

    6/49

    38 begin39 Pu t _L i ne ( " Run s t a rt e d" ) ;40 f or i i n T he se R a ng e l o op41 S t a rt e r : = new Wor ke r ( The s e ( i ) );42 e nd l o op ;43 Put_Line("Run Fin i shing " ) ;44 e nd Run_Conc u r r e n tl y ;45

    46 begin47 Pu t _L i ne ( " M a i n s t a rt e d" ) ;48 Run_Concur rent ly ( (Oneaccess , Two access ,49 Three access )) ;

    50 Pu t _L i ne ( " M a i n F i n is he d" ) ;51 e nd M a in ;

    Question 4.2Although arrays of tasks can be created easily, assigning values to theirdiscriminants is awkward. An early version of Ada 95 incorporated newsyntax to allow this; however, during the languages scope reduction, thiswas removed. The same effect can be achieved by calling a function witha side effect.

    1 p a c ka ge Coun t i s2 f unct i on As s ign_Num be r re t u rn I nde x ;3 e nd Coun t ;4

    5 t as k t y pe X ( I : I nd ex : =6 Count .Ass ign_Number ) ;7

    8 t yp e X A i s a r ra y ( I n de x ) o f X ;

    Where the body of Count is1 p a ck a ge b od y C ou n t i s2 Num be r : I ndex : = I nde x F i r s t ;3 f unct i on As s i gn_Num be r r e t ur n I nde x is4 begin5 r e t ur n Num be r ;6 N um be r : = N um be r + 1 ;7 e nd As s i gn_Num be r ;8 e nd Coun t ;9

    10 X t as k s : X A ;

    Question 4.3For two tasks:

    1 p r oce dur e Cobeg i n i s2

    3 t as k A ;4 t as k B ;5

    6 t as k bo d y A is s ep ar a te ;7 t as k bo d y B is s ep ar a te ;

    6

  • 8/13/2019 Real Time System and Programming Langauges

    7/49

    8 begin9 nul l ;

    10 e nd Cobe g i n ;

    Question 4.4A fork is simply creation of a process dynamically. This can be doneeasily in Ada. The join is more problematic. Notionally, given the iden-tity of the task created, the parent can busy-wait using the terminatedag. However, if busy-waiting is to be avoided then some form of IPCmechanism must be used.

    Question 4.5

    211 we think !

    Question 4.9The following points need to be made:

    an exception will not propagate beyond a task, even if it caused thetask to terminate

    a scope cannot exit (even to propagate an exception) if they are noneterminated tasks dependent on that scope.

    an exception raised in the elaboration of the declarative part of atask will cause that task to fail (without beginning its execution);moreover the parent of that task will have tasking error raisedbefore it can state executing.

    These points are illustrated by the behaviour (output) of the program. If C = 2 then no exceptions are raised and the following output is generated:A StartedMain Procedure StartedP StartedP Finished(* DELAY 10 second *)

    T FinishedA Finished

    Note the output Main Procedure Started could occur rst second orthird.

    When C = 1 then the procedure P will fail. But the exception (con-straint error or numeric error) cannot propagate for 10 seconds until taskT has completed. Its propagation will cause A to fail (hence no A nishedmessage) but the main program will be unaffected:A StartedMain Procedure StartedP Started(* DELAY 10 second *)T Finished

    7

  • 8/13/2019 Real Time System and Programming Langauges

    8/49

    Finally when C=0 then A will fail during elaboration of its declarativepart and hence it will never start to execute; moreover the main programwill get tasking error raised at its starts and hence it will not begin. Theoutput is simply:Main Procedure Failed

    Question 4.10For task A, the parent is the main task, its children are C and D, its masteris Hierarchy and its dependents are C and D.

    For task Pointerb.all , the parent is C, it has no children, its masteris Hierarchy and it has no dependents.

    For task Another Pointerb.all , the parent is D, it has no children, itsmaster is Hierarchy and it has no dependents.

    For task C, the parent is A, its child is Pointerb.all , its master is Aand it has no dependents.

    For task D, the parent is A, its child is Another Pointerb.all , itsmaster is A and it has no dependents.

    Procedure Main has no direct parent, children, master or dependentsProcedure Hierarchy has no direct parent, children, or master. Its

    dependents are A, Pointerb.all , and Another Pointerb.all .

    Question 4.12MyCalculation.run(); runs the run procedure sequentially.

    whereas the

    new Thr ea d ( M yCa l c u l a t i on ). s t a r t ( ) ;

    will create a new thread.

    Question 5.2The algorithm works by keeping four slots for the data: two banks of twoslots. The reader and the writer never access the same bank of slots at thesame time. The atomic variable Latest contains the index of the bank to

    which the last data item was written and the Next Slot array indexed bythis value indicates which slot in that bank contains the data.

    1. a Write is followed by a Read the reader gets the last value written

    2. a Read is preempted by a Write the writer will write to a differentbank of slots than being accessed by the current reader.

    3. a Write is preempted by a Read the reader will read from a differ-ent bank of slots than being accessed by the current writer.

    4. a Read is preempted by more than on Write the rst writer willwrite to one of the slots in the bank which is not being currentlyread, the other will write into the other slot.

    8

  • 8/13/2019 Real Time System and Programming Langauges

    9/49

    5. a Write is preempted by more than one Read all the readers willread from the same slot in the bank other than the one being writtento.

    Consider some arbitrary time when the latest value of the data itemis in Four Slot(Second, First) . In this case Latest equals Second andNext(Second) = First . Assume also that this is the last value read. If another read request comes in and is interleaved with a write request, thewrite request will chose the rst bank of slots and the rst slot, and so on.Thus it is possible that the reader will obtain an old value but never aninconsistent one. If the write comes in again before the read has nished,it will write to the rst bank and second slot, and then the rst bank andrst slot. When the reader next comes in, it will obtain the last valuethat was completely written (that is, the value written by the last fullinvocation of Write ).

    Question 5.3

    var mutex( initial 1);wrt( initial 1);readcount := 0;

    (* reader processes *)

    P(mutex)readcount := readcount +1;if readcount = 1 then P(wrt);

    V(mutex)

    (* read data structure *)

    P(mutex)readcount := readcount -1;if readcount = 0 then V(wrt);

    V(mutex)

    (* writer processes *)

    P(wrt)(* write data structure *)

    V(wrt)

    Question 5.4Hoares conditional critical region is of the form:region x when B do S1;

    In the following solution: x wait is a semaphore used for processeswaiting for their guard to be TRUE; and x count is the number waiting.When the region is left we scan down the queue to see if any process cancontinue. We use x temp to keep track of the number of processes wehave rescheduled (otherwise we would just loop).

    9

  • 8/13/2019 Real Time System and Programming Langauges

    10/49

    var x_mutex semaphore ( initial 1);x_wait semaphore ( initial 0);

    x_count : integer :=0;x_temp : integer :=0;

    P(x_mutex)if not B then

    x_count := x_count +1;V(x_mutex);P(x_wait);while not B do

    x_temp := x_temp +1;if x_temp =< x_count thenV(x_wait);

    elseV(x_mutex);

    end if ;P(x_wait);

    end loop ;x_count := x_count -1;

    end if ;

    S1;

    if x_count > 0 thenx_temp := 1;V(x_wait);

    elseV(x_mutex);

    end ;

    Question 5.5

    For mutual exclusion: mutex : semaphore(initial 1);

    For signalling processes suspended:next : semaphore(initial 0);

    For each condition:x_sem : semaphore(0);

    Counts:next_count : integer :=0;

    x_count : integer :=0;For each procedure:

    P(mutex);body;

    if next_count > 0 thenV(next);

    elseV(mutex);

    end if ;

    For each wait on condition x

    x_count := x_count +1;if next_count > 0 then

    10

  • 8/13/2019 Real Time System and Programming Langauges

    11/49

    V(next);else

    V(mutex);P(x_sem);x_count := x_count -1;

    For each signal on condition x

    if x_count > 0 thennext_count := next_count + 1;V(x_sem);P(next);

    next_count := next_count - 1;end if ;

    Question 5.6

    interface module semaphores;dene semaphore, P, V, init;type semaphore = record taken : boolean;

    free : signal;end ;

    procedure P(var s:semaphore);begin

    if s.taken then wait(s.free) end ;

    s.taken := true;end P;

    procedure V( var s:semaphore);begin

    s.taken := false;send(s.free);

    end ;

    procedure init( var s:semaphore)begin

    s.taken := false;end ;

    end ;

    To extend to the general semaphore the boolean becomes a count. Inittakes an initial value of type integer. P only blocks when the count is 0.

    Question 5.7The criticism of condition synchronisation is that wait and signal are likesempahore operations and therefore unstructured. A signal on the wrongcondition may be difficult to detect. They are therefore too low level andunstructured.

    The WaitUntil primitive removes the need for condition variables andtherefor wait and signal. the problem how to implement it. If a process

    11

  • 8/13/2019 Real Time System and Programming Langauges

    12/49

    is blocked because its boolean expression is false then it must give up themonitor lock to allow other processes to enter and change the variablesin the expression. So the issue is when to re-evaluate the guards. Asthe monitor does not know if the variables in a boolean expression havebeen altered, all boolean expressions must be revaluated EVERY TIMEa process releases the monitor lock. This is inefficient and therefore notused.

    The object to this approach may be invalid if we have a multi processorsystem with shared memory where each processor only executes a singleprocess. If this is the case then the process can continually check itsguards as the processor is unable to execute another process.buffer_controller : monitor

    type buffer_t is recordslots : array (1..N) of character;size : integer range 0..N;head, tail : integer range 1..N;

    end record ;

    buffer : buffer_t;

    procedure produce(char : character);...WaitUntil buffer.size < N

    -- place char in bufferend ;

    function consume return character;...WaitUntil buffer.size > 0

    -- take char out of buffer;return char;

    end;end;

    Question 5.8

    Here we show a solution in the Modula language.MODULE smokers ;

    TYPEingredients = (TOBandMAT,TOBandPAP,PAPandMAT);

    INTERFACE MODULE controller;DEFINE get, put, release;USE ingredients;VAR

    TP, MP, PP : signal;TAM, TAP, PAM : signal;

    PROCEDURE get ( ingred : ingredients);BEGIN

    12

  • 8/13/2019 Real Time System and Programming Langauges

    13/49

    (* called by smokers *)CASE ingred OF

    TOBandMAT: BEGIN(* Paper Process *)IF NOT awaited(PP) THEN

    wait(TAM)END;(* ingredients available *)

    END;

    TOBandPAP: BEGIN(* Matches Process *)

    IF NOT awaited(MP) THENwait(TAP)

    END;(* ingredients available *)

    END;

    PAPandMAT: BEGIN(* Tobacco Process *)IF NOT awaited(TP) THEN

    wait(PAM)END;(* ingredients available *)

    ENDEND

    END get;

    PROCEDURE release ( ingred : ingredients);BEGIN

    (* called by smokers *)(* releases agent *)

    CASE ingred OFTOBandMAT: BEGIN

    (* Paper Process *)send (PP)

    END;

    TOBandPAP: BEGIN(* Matches Process *)send (MP)

    END;

    PAPandMAT: BEGIN(* Tobacco Process *)send (TP)

    ENDEND

    END release;

    PROCEDURE put ( ingred : ingredients);BEGIN

    (* called by agent *)(* place ingredients on the table *)CASE ingred OF

    TOBandMAT: BEGIN(* looking for Paper Process *)IF awaited(TAM) THEN

    13

  • 8/13/2019 Real Time System and Programming Langauges

    14/49

    send(TAM)END;wait(PP)

    END;

    TOBandPAP: BEGIN(* Matches Process *)IF awaited(TAP) THEN

    send(TAP)END;wait(MP)

    END;

    PAPandMAT: BEGIN(* looking for Tobacco Process *)IF awaited(PAM) THEN

    send(PAM)END;wait(TP)

    ENDEND

    END put;END controller;

    PROCESS smoker (requires : ingredients);BEGIN

    LOOPcontroller.get(requires);

    (* roll and smoke cigarette *)controller.release(requires)

    ENDEND smoker;

    BEGINsmoker(TOBandMAT);smoker(TOBandPAP);smoker(PAPandMAT)

    END smokers.

    Question 5.10

    #include "mutex.h"

    typedef structpthread_mutex_t mutex;pthread_cond_t ok_to_read;pthread_cond_t ok_to_write;int readers;int writing;int waiting_writers;/* data */

    shared_data;

    int start_read(shared_data *D)PTHREAD_MUTEX_LOCK(&D->mutex);while(D->writing > 0 || D->waiting_writers > 0)

    14

  • 8/13/2019 Real Time System and Programming Langauges

    15/49

    PTHREAD_COND_WAIT(&(D->ok_to_read), &(D->mutex));

    D->readers++;PTHREAD_MUTEX_UNLOCK(&D->mutex);return 0;

    ;

    int end_read(shared_data *D)PTHREAD_MUTEX_LOCK(&D->mutex);if(--D->readers == 0 )

    PTHREAD_COND_SIGNAL(&D-> ok_to_write);;

    PTHREAD_MUTEX_UNLOCK(&D->mutex);return 0;

    int start_write(shared_data *D)PTHREAD_MUTEX_LOCK(&D->mutex);D->waiting_writers++;while(D->writing > 0 || D->readers > 0)

    PTHREAD_COND_WAIT(&(D->ok_to_write), &(D->mutex));

    D->writing++;D->waiting_writers--;PTHREAD_MUTEX_UNLOCK(&D->mutex);return 0;

    ;

    int end_write(shared_data *D)PTHREAD_MUTEX_LOCK(&D->mutex);D->writing = 0;if(D->waiting_writers != 0 )

    PTHREAD_COND_SIGNAL(&D-> ok_to_write);

    elsePTHREAD_COND_BROADCAST(&D-> ok_to_read);

    PTHREAD_MUTEX_UNLOCK(&D->mutex);return 0;

    int main()/* ensure all mutexes and condition

    variables are initialised */

    Question 5.11

    #include "mutex.h"

    const int N = 32;typedef struct

    pthread_mutex_t mutex;pthread_cond_t free;int free_resources;

    15

  • 8/13/2019 Real Time System and Programming Langauges

    16/49

    resource;

    void allocate(int size, resource *R)pthread_mutex_lock(&R->mutex);

    while(size > (R->free_resources))pthread_cond_wait(&(R->free), &(R->mutex));

    R->free_resources = R->free_resources - size;pthread_mutex_unlock(&R->mutex);

    void deallocate(int size, resource *R)

    pthread_mutex_lock(&R->mutex);R->free_resources = R->free_resources + size;pthread_cond_broadcast(&R-> free);

    pthread_mutex_unlock(&R->mutex);

    void initialize(resource *R)R->free_resources = N;/* initialise mutex and condition variables */

    Question 5.14

    1 w i t h a da . t e x t_ i o ; u s e a da . t e x t _ io ;2 w i t h a da . e xc ep t i ons ; u s e a da . e xce p t ions ;3 w i t h a da .num e ri c s . d i s c r e t e _ r a ndom ;4 p r oce dur e s m oke r s 2 i s5

    6 t yp e n ee d is ( t_ p , t_ m , m_ p ) ;7 p a c ka ge s m ok i ng_ i o i s ne w e nume r a t i on_ i o ( ne e d ) ;8 p a c ka ge r a ndom _i ng re d i e n t s i s ne w9 ada .numer ics .d i scre te_random(need) ;

    10

    11 t as k t yp e s m ok e r ( m y_ n ee d s : n e ed ) ;12

    13 t a s k a c t i ve _a ge n t ;14

    15 p r o te c t ed a ge n t i s16 p r oce du re g i ve ( i ng r e di e n t s : n e e d ) ;17 e n tr y g iv e _ ma t c he s ( n : n ee d ; o k : ou t b oo l ea n ) ;18 e n tr y g i ve _ pa pe r ( n : n ee d ; o k : o ut b o o le a n ) ;19 e n tr y g iv e _ to b a cc o ( n : n ee d ; o k : ou t b oo l ea n ) ;20 p r oce du re c i ga r e tt e _ f i n i she d ;21 e n t ry wa i t _ s moke r s ;22 pr ivate23 t _ava i l able , m_avai lable ,24 p _ av a il a bl e : b oo l ea n : = f al s e ;25 a l loca ted_t , a l loca ted_p ,26 a l l oc a te d_m : boo le a n ;27 a l l_ d on e : b oo l ea n : = f al s e ;28 i ng re d i en t s : n e ed ;29 e nd a ge nt ;30

    31 t as k bo d y s m ok e r i s

    16

  • 8/13/2019 Real Time System and Programming Langauges

    17/49

    32 g ot : b o ol e an ;33 begin34 smoking_io .put (my_need s ) ;35 loop36

    37 g ot : = f al s e ;38

    39 c a s e m y_ne e ds i s40 w h en t _p = >41 w h il e n ot g ot l oo p42 agent .g ive_tobacco (my_needs , got ) ;43 d e la y 0 .1 ;

    44 e nd l o op ;45 agent .g ive_paper (my_needs , got ) ;46 w h en t _m = >47 w h il e n ot g ot l oo p48 agent .g ive_tobacco (my_needs , got ) ;49 d e la y 0 .1 ;50 e nd l o op ;51 agent .g ive_ma tches(my_needs , got ) ;52 w h en m _p = >53 w h il e n ot g ot l oo p54 agent .g ive_matches (my_needs , got ) ;55 d e la y 0 .1 ;56 e nd l o op ;57 agent .g ive_paper (my_needs , got ) ;58 e nd c a s e ;59 i f n ot g ot th en r a is e p r o gr a m _e r ro r ; e nd i f ;60 - - m a ke a nd s m ok e c i g ar e t te61 smoking_io .put ( my_needs ) ; put_ l ine(" smoking!") ;62 d e l ay 1 .0 ;63 agent .c igare t t e_f in i shed;64 e nd l oop ;65 exception66 w h en e : o t he r s = >67 put (except ion_name(e) ) ;68 p ut ( " e xc e pt i on c a ug h t i n " ) ;69 smoking_io .put ( my_needs ) ;put_ l ine(" smoker") ;70 e nd s m oke r ;71

    72 t as k bo d y ac t iv e _ ag e n t i s73 g e n : ra ndom _i ng r e d i e nt s . ge ne r at o r ;74 i ng re d i en t s : n e ed ;75 begin76 r andom_ingredient s . rese t (gen) ;77 loop78 - - c ho s e t w o i te m s r a nd o m ly a n d s e t79 - - t _a va il a b le , m _ava i la b l e , p_a va i la b l e to80 - - t r ue o r f a ls e c o r re s p on d in g l y 81 i ng re d ie n t s : = r a ndom _i ng r e d i en t s . r a ndom ( ge n ) ;82 agent .g ive( ingredient s ) ;83 agent .wai t_smokers ;84 e nd l oop ;85 e nd a c t i ve _age n t ;86

    87 p ro t ec t ed b o d y ag en t is88 p r oce du re g i ve ( i ngr e di e n t s : n e e d ) i s

    17

  • 8/13/2019 Real Time System and Programming Langauges

    18/49

    89 begin90 c a s e i ng re d ie n t s i s91 w h en t _p = >92 t _ a va i la b l e : = t r ue ;93 p_a va i la b l e : = t r ue ;94 m _a va i la b l e : = f a l se ;95 p ut ( " a g en t h as " ) ;96 w h en t _m = >97 t _ a va i la b l e : = t r ue ;98 m _a va i la b l e : = t r ue ;99 p_a va i la b l e : = f a l se ;

    100 w h en m _p = >

    101 m _a va i la b l e : = t r ue ;102 p_a va i la b l e : = t r ue ;103 t _ a va i la b l e : = f a l se ;104 e nd c a s e ;105 put ( "agent has " ) ; smoking_io .put ( ingredient s ) ;106 pu t_ l i ne ( " f or s m oke r s " ) ;107 a l loc a te d_ t : = f a l se ;108 a l loc a te d_p : = f a l se ;109 a l loc a te d_m : = f a l se ;110 e nd g i ve ;111

    112 e n tr y gi v e _t o b ac c o (n : ne e d ; o k : ou t b oo l ea n )113 whe n t _a va i l ab l e a nd no t a l loc a te d_ t i s114 begin115

    116 i f ( a ll oc at ed _m an d n = t _m ) o r117 ( a ll oc at ed _p a nd n = t _p ) o r118 ( m _a va il ab le a nd n = t _m ) o r119 ( p _ av a il a bl e a nd n = t _p ) t he n120 o k : = t ru e ;121 a l l oc a t ed_ t : = t r ue ;122 else123 o k : = f al s e ;124 e nd i f ;125 i f o k t he n126 p ut ( " a g en t : g i ve n o ut t o ba c co t o " ) ;127 s m oki ng_i o . pu t ( n ) ; pu t_ l i ne ( " s m oke r " ) ;128 else129 p ut ( " a g en t : r e fu s in g t o ba cc o t o " ) ;130 s m oki ng_i o . pu t ( n ) ; pu t_ l i ne ( " s m oke r " ) ;131 e nd i f ;132 e nd g i ve _ t oba c c o ;133

    134 e nt ry gi ve _m a tc he s (n : n ee d ; o k : o ut bo ol ea n )135 w h en m _ av a il a bl e a nd n ot a ll o ca t ed _ m i s136 begin137 i f ( a ll oc at ed _t a nd n = t _m ) o r138 ( a l lo c at e d_ p a nd n = m _p ) o r139 ( t _ av a il a bl e a nd n = t _m ) o r140 ( p _ av a il a bl e a nd n = m _p ) t h en141 o k : = t ru e ;142 a l l oc a t ed_m : = t r ue ;143 else144 o k : = f al s e ;145 e nd i f ;

    18

  • 8/13/2019 Real Time System and Programming Langauges

    19/49

    146 i f o k t he n147 p ut ( " a g en t : g i ve n o ut m a tc h es t o " ) ;148 s m oki ng_i o . pu t ( n ) ; pu t_ l i ne ( " s m oke r " ) ;149 else150 p ut ( " a g en t : r e fu s in g m a tc he s t o " ) ;151 s m oki ng_i o . pu t ( n ) ; pu t_ l i ne ( " s m oke r " ) ;152 e nd i f ;153 e nd g i ve _m a tc he s ;154

    155 e nt r y g iv e _p a pe r ( n : n e ed ; o k : o ut bo o le a n )156 w h en p _a v ai l ab l e a nd n ot a l lo c at e d_ p i s157 begin

    158 i f ( a ll oc at ed _m a nd n = m _p ) o r159 ( a l lo c at e d_ t a nd n = t _p ) o r160 ( m _ av a il a bl e a nd n = m _p ) o r161 ( t _a va il ab le a nd n = t _p ) t he n162 o k : = t ru e ;163 a l l oc a t ed_p : = t r ue ;164 else165 o k : = f al s e ;166 e nd i f ;167 i f o k t he n168 p ut ( " a g en t : g i ve n o ut p a pe r t o " ) ;169 s m oki ng_i o . pu t ( n ) ; pu t_ l i ne ( " s m oke r " ) ;170 else171 p ut ( " a g en t : r e fu s in g p a pe r t o " ) ;172 s m oki ng_i o . pu t ( n ) ; pu t_ l i ne ( " s m oke r " ) ;173 e nd i f ;174 end g ive_paper ;175

    176 p r oce du re c i ga r e t te _ f i n i she d i s177 begin178 a l l_ d on e : = t r ue ;179 end;180

    181 e n t ry wa i t _ s moke r s whe n a l l _done i s182 begin183 a l l _done : = f a l se ;184 e nd wa i t _ s m oke r s ;185

    186 e nd a ge nt ;187

    188 t p : s mo k er ( t _ p );189 t m : s mo k er ( t _ m );190 m p : s m oke r ( m _p) ;191

    192 begin193 nul l ;194 e nd s m oke r s2 ;

    Question 5.17Client tasks call the Wait entry and are queued until there are Needednumber of tasks. At which point they are all released. The value of Needed is determined when an instance of the protected type is created.

    1 w i th P t hr e ad s ; u se P th r ea d s ;

    19

  • 8/13/2019 Real Time System and Programming Langauges

    20/49

    2 p a c ka ge Ba r r i e rs i s3

    4 t yp e B a r ri er ( N e e de d : P o si t iv e ) i s l im i te d p r iv a te ;5

    6 p ro c ed u re Wa it ( B : i n ou t B a rr i er ) ;7 p r oce du re I n i ti a li s e ( B : i n out Ba r ri e r ) ;8

    9 pr ivate10

    11 t yp e B a rr i er ( N e e de d : P o si t iv e ) i s12 record13 M : M ut ex _T;

    14 C : C on d_ T;15 A r ri v ed : N a tu r al ;16 e nd r e c or d ;17

    18 e nd Ba r r i e rs ;19

    20 p a ck a ge b od y B ar r ie r s i s21

    22

    23 p ro c ed u re Wa it ( B : i n ou t B a rr i er ) i s24 begin25 mutex_lock (B.M );26 B . A r ri v ed := B . A rr i ve d + 1 ;27 i f A rr i ve d = B . N ee d ed th e n28 B . A rr i ve d : = 0 ;29 Cond_Broadcas t (B.C) ;30 else31 Cond_Wai t (B.C, B.M);32 e nd i f ;33 mutex_unlock(B.M);34 e nd Wa i t ;35

    36

    37 p ro c ed u re I n it i al i se ( B : i n o u t B a rr i er ) i s38 begin39 Mutex_Ini t i a l i se (B.M);40 Cond_Ini t i a l i se (B.C) ;41 end In i t i a li se ;42

    43 e nd Ba r r i e rs ;

    Question 5.18

    1 p a c ka ge body M ULTI CAST i s2

    3 p a c ka ge COND_SEM i s new SEM APHORE_PACKAGE( 0 ) ;4 p a c ka ge BI NARY_SEM i s ne w SEM APHORE_PACKAGE( 1 );5

    6 u s e BI NARY_SEM ; u s e COND_SEM ;7

    8 DATA_AVAI LABLE : COND_SEM . SEM APHORE ;9 MUTEX : BINARY_SEM .SEMAPHORE ;

    10 WAI T IN G : I NT E GE R : = 0 ;

    20

  • 8/13/2019 Real Time System and Programming Langauges

    21/49

    11

    12 THE_DATA : I NTEGER;13 p ro c ed u re S E ND ( I : I NT EG E R ) is14 begin15 WAIT(MUTEX);16 T H E_ D ATA : = I ;17 i f WAI TI NG / = 0 t he n18 SIGNAL(DATA_AVAILABLE) ;19 else20 SIGNAL(MUTEX);21 e nd i f ;22 end;

    2324 p r oce du re RECEI VE( I : out I NTEGER) is25 begin26 WAIT(MUTEX)27 WA IT I NG : = WA IT I NG + 1 ;28 SIGNAL(MUTEX);29 WAIT(DATA_AVAILABLE) ;30 WA IT I NG : = WAI T IN G - 1;31 I : = T HE _ DATA ;32 i f WAI TI NG /= 0 t he n33 SIGNAL(DATA_AVAILABLE) ;34 else35 SIGNAL(MUTEX)36 e nd i f ;37 e nd RECEI VE;38

    39 end MULTICAST ;

    Question 5.19

    1 p a c ka ge body BROADCAST i s2

    3 p a c ka ge COND_SEM i s new SEM APHORE_PACKAGE( 0 ) ;4 p a c ka ge BI NARY_SEM i s ne w SEM APHORE_PACKAGE( 1 );5

    6 u s e BI NARY_SEM ; u s e COND_SEM ;7

    8 DATA_AVAI LABLE : COND_SEM . SEM APHORE ;9 RECEI VERS_READY : COND_SEM .SEM APHORE ;

    10 MUTEX : BINARY_SEM .SEMAPHORE ;11 NEW_SEND : BINARY_SEM .SEMAPHORE ;12 WAI T IN G : I NT E GE R : = 0 ;13

    14 THE_DATA : I NTEGER;15

    16 p ro c ed u re S E ND ( I : I NT EG E R ) is17 begin18 WAIT(NEW_SEND ) ;19 WAIT(MUTEX);20 T H E_ D ATA : = I ;21 i f WAI TI NG = 1 0 t he n22 SIGNAL(DATA_AVAILABLE) ;23 else24 SIGNAL(MUTEX);25 WAIT(RECEIVERS_READY);

    21

  • 8/13/2019 Real Time System and Programming Langauges

    22/49

    26 e nd i f ;27 SEND(NEW_SEND ) ;28 end;29

    30 p r oce du re RECEI VE( I : out I NTEGER) is31 begin32 WAIT(MUTEX)33 WA IT I NG : = WA IT I NG + 1 ;34 i f WAI T IN G = 1 0 t h en S I GN AL ( R E C E I VE R S _R E A DY ) ;35 else36 SIGNAL(MUTEX);37 WAIT(DATA_AVAILABLE) ;

    38 e nd i f ;39 I : = T H E_ D ATA ;40 WA IT I NG : = WA IT I NG - 1;41 i f WAI TI NG / = 0 t he n42 SIGNAL(DATA_AVAILABLE) ;43 else44 SIGNAL(MUTEX)45 e nd i f ;46 e nd RECEI VE;47

    48 end BROADCAST ;

    Question 5.20

    1 p r o te c te d To t al _Coun t i s2 p r oce du re Ca r _ I n ( Uppe r _J us t _Pa s s e d : out Boo le a n ) ;3 p r oce du re Ca r _Ou t ( Lo we r _J us t _Pa s s e d : out Boo l ea n ) ;4 pr ivate5 Tot a l_ C ar s : N a t ur a l := 0 ;6 Uppe r _Thr e s ho ld_Pa s s e d : Bool e a n := Fal s e ;7 Lowe r _Thr e s ho ld_Pa s s e d : Bool e a n := Fal s e ;8 end Tota l_Count ;9

    10 p r o te c te d body To t a l_Coun t i s11 p r oce du re Ca r _ I n ( Uppe r _J us t _Pa s s e d : out Boo le a n ) i s12 begin13 To ta l _C ar s := To ta l _C a rs + 1 ;14 i f To ta l _Ca r s >= M a x i m um_Ca r s _ I n_Ci t y_For _Re d_Li gh t15 a nd t he n no t Uppe r _Thr e s ho l d_Pa s s e d t he n16 Uppe r _Thr e s ho l d_Pa s s e d : = Tr ue ;17 Uppe r _J us t _Pa s se d : = Tr ue ;18 Lowe r _Thr e s ho l d_Pa s s e d : = Fa l se ;19 else20 Uppe r _J us t _Pa s se d : = Fa l se ;21 e nd i f ;22 e nd Ca r _I n ;23

    24 p r oce du re Ca r _Ou t ( Lo we r _J us t _Pa s s e d : ou t Boo l e an ) i s25 begin26 To ta l _C ar s := To ta l _C a rs - 1 ;27 i f To ta l _Ca r s

  • 8/13/2019 Real Time System and Programming Langauges

    23/49

    32 else33 Lowe r _Thr e s ho l d_Pa s s e d : = Fa l se ;34 e nd i f ;35 e nd Ca r _ou t ;36 end Tota l_Count ;37

    38 t a sk b o dy B a r _C o nt r o ll e r i s39 C i t y_J us t _Fu l l : Bool e a n ;40 C i t y_J us t _Spa ce : Boo le a n ;41 begin42 loop43 C i t y_J us t _Fu l l : = Fa l se ;

    44 C i t y_J us t _Spa c e : = Fa l se ;45 select46 a c c ep t Ca r_En te r e d do47 Tota l_Count .Car_In( Ci ty_Jus t_Ful l ) ;48 end Car_Entered ;49 or50 a c c ep t Ca r_Ex it e d do51 Tota l_Count .Car_Out ( Ci ty_Jus t_Space ) ;52 end Car_Exi ted ;53 e nd s e l ec t ;54 i f C i t y_J us t _Fu l l t he n55 Ci ty_Traff i c_Light s_Cont ro l l e r.Ci ty_Is_Ful l ;56 e l s if C i t y_J us t _Spa c e t he n57 Ci ty_Traff i c_Light s_Cont ro l l e r.Ci ty_Has_Space ;58 e nd i f ;59 e nd l oop ;60 e nd Ba r _Cont r o l l e r ;

    Question 5.22

    pub li c c l as s Re a de r sWr i t e r s2{

    p ri v at e i nt r ea d er s = 0 ;p ri v at e i nt w a it i n gR e a de r s = 0 ;p ri v at e i nt w a it i n gWr i te r s = 0 ;p ri v at e b o ol e an w r it i ng = f a ls e ;

    Cond i t ionVa r i ab l e OkToRe a d = ne w Cond i t i onVa r i a bl e ( ) ;Cond i t ionVa r i ab l e OkToWr i te = ne w Cond i t ionVa r i ab l e ( ) ;

    pub li c vo i d s t a rt Wr it e ( ) t h r ows I n t e r r upt e dExc ep t i on{

    synchronized( OkToWri te ) / / g e t l o ck o n c o nd i t io n v a r ia b l e{

    synchronized( th i s ) / / g e t m o ni t o r l o c k {

    i f( w ri ti ng | r ea de rs > 0 | w a it in g Re ad e rs > 0 ) {wai t ingWri te r s++;OkToWr i te .wa n t ToS l ee p = t r ue ;

    } el se {w r it i ng = t ru e ;OkToWr i te .wa n t ToS l ee p = f a l se ;

    }} / / g iv e u p m o n it o r l oc k

    23

  • 8/13/2019 Real Time System and Programming Langauges

    24/49

    i f (OkToWri te .wantToSleep ) {OkToWrite .wait() ;

    }}

    }

    pub li c vo i d s t opWr i te ( ){Sys tem.out .pr in t ln("StopWri te Cal led ") ;

    synchronized(OkToRead)

    { synchronized( OkToWri te ){

    synchronized( th i s ){

    i f ( w ai t i ng R ea d e rs > 0 ) {w r it i ng = f a ls e ;r e a de r s = wa i t i ngRe a de r s ;w a i ti n g Re a d er s = 0 ;OkToRead.not i fyAl l ( ) ;

    } e ls e i f( w a it i ng Wr i te rs > 0 ) {wait ingWriters -- ;OkToWri te .not i fy( ) ;

    } e ls e w ri ti ng = f al se ;}

    }

    }}

    pub li c s ync h r on i z e d vo i d s t a rt Re ad ( )t h r ows I n t e r r upt e dExc ep t i on

    {s ync h r on i z e d ( OkToRe ad ) {

    synchronized( th i s ){

    i f ( wr it i ng ) {wai t ingReaders++;OkToRe a d .wa n t ToS l ee p = t r ue ;

    } e ls e {readers++;OkToRe a d .wa n t ToS l ee p = f a l se ;

    }}i f (OkToRead. wantToSleep ) {

    OkToRead.wai t ( ) ;}

    }}

    pub li c s ync h r on i z e d vo i d s t opRe a d ( ){

    synchronized( OkToWri te ){

    synchronized( th i s ){

    readers -- ;

    24

  • 8/13/2019 Real Time System and Programming Langauges

    25/49

    i f( r ea de rs = = 0 & w ai t in gW r it er s > 0 ) {wait ingWriters -- ;w r it i ng = t ru e ;OkToWri te . not i fy( ) ;

    }}

    }}

    }

    Question 5.23

    pub li c c l as s Re s ou r ce M a na ger{

    p ri v at e f i na l i nt m a xR e s ou r c es = 1 5;p r o te c t ed i n t r e s ou r c es Fr e e ;

    pub li c Re s ou r ce M a na ge r (){

    r e s ou r ce s Fr e e = m a xRe s ou r c e s ;}

    pub li c s ync h r on i z e d vo i d a l l oc a t e ( i n t s i z e ) t h r owsTooM a nyRe s ou r c es Re que st e d , I n t e r r up t e dExce p t i on

    {i f ( si z e > m a xR e s ou r c es ) t h ro w n ew

    TooManyResourcesReques ted( ) ;w h il e ( s iz e > r e s ou r c es F re e ) {

    wai t ( ) ;}r e s ou r ce s F re e = r e so u r ce s F re e - s iz e ;

    }

    pub li c s ync h r on i z e d vo i d de a ll oc at e ( i n t s i z e ){

    r e s ou r ce s F re e = r e so u r ce s F re e + s iz e ;Sys te m .ou t . p r i n tl n ( " r e s ou rc e s l e f t " + r e s ou r ce s Fr e e );not ifyAll () ;

    }}

    Question 5.24

    pub li c c l as s Qua n t i tySe m a phor e{

    i n t va l ue ;

    pub li c Qua n t i tySe m a phor e ( i n t I ){

    v al ue = I ;}

    p ub l ic s y nc h r on i z ed v o id w a it ( i nt I )

    25

  • 8/13/2019 Real Time System and Programming Langauges

    26/49

    {t ry {

    w h il e ( I > v a lu e ) w a it ( ) ;v al ue = v al ue - I ;

    }c a tc h ( E x ce p ti o n E ) { } ;

    }

    pub li c s ync h r on i z e d vo i d s i gna l ( i n t I ){

    v al ue = v al ue + I ;not ifyAll () ;

    }}

    Question 5.25Given the class specication, it would be very messy to implement thealgorithm. It would be necessary to keep a count of high priority waiters.The signaller would notifyAll. All low priority waiters would wait againif there were high priority waiters. High priority waiters would need todecide amongst themselves wich one should continue, the others wouldwait again.

    If we change the specication so that the methods are not synchro-nized, then the following solution is possible.

    pub li c c l as s Even t{

    p r i va t e i n t h i ghPr io r i t yWa it i ng ;p r i va t e i n t l owPr i or i t yWa i ti ng ;p r i va t e Cond i t ionVa r i a bl e h i ghWa i te r ;p r i va t e Cond i t ionVa r i a bl e l owWa i t er ;

    pub li c Eve nt ( ){

    h i ghPr io r i t yWa it i ng = 0 ;l owPr i or i t yWa i ti ng = 0 ;h i ghWa i te r = ne w Cond i t ionVa r i a bl e ( ) ;l owWa i t er = ne w Cond i t ionVa r i a bl e ( ) ;

    }

    p ub l ic v o id h i g hP r io r i ty Wa it ( )

    { synchronized( highWai ter ) {s ync h r oni z e d ( t h is ) {

    highPr ior i tyWai t ing++;}t ry {

    highWaiter .wait() ;} c at c h ( Ex c ep t io n E ) { };

    }};

    pub li c s ync h r on i z e d vo i d l owPr i or i t yWa i t (){

    synchronized( lowWai ter ) {

    26

  • 8/13/2019 Real Time System and Programming Langauges

    27/49

    s ync h r oni z e d ( t h is ) {lowPr ior i tyWai t ing++;

    }t ry {

    lowWaiter .wait() ;} c at c h ( Ex c ep t io n E ) { };

    }};pub li c s ync h r on i z e d vo i d s i gna l Eve n t ( ){

    synchronized( highWai ter ) {synchronized( lowWai ter ) {

    s ync h r on i z e d ( t h is ) {i f ( h ig h P ri o r it y Wai t in g > 0 ) {

    highWai te r . not i fy( ) ;h ighPr ior i tyWai t ing - - ;

    } e ls e i f ( l o wP ri o ri ty Wai ti n g > 0 ) {lowWai ter . not i fy( ) ;lowPr iori tyWai t ing - - ;

    }}

    }}

    };}

    To modify this, so that an individual thread is woken, requires a noti-fyAll, and each thread to test an indended ID with their own Id. Messy.

    Question 6.1Yes: protected objects are exible, they can implement semaphores, andtherefore can implement the same expressive power as the rendezvous.

    No: Although it may have the same expressive power, it is not easyto program a selective waiting construct. It is not possible for example tohave a multi-way select and therefore the ease of use is sacriced.

    Question 6.2

    NO, each queue is in FIFO order, there is no time information available.

    Question 6.3

    1 s u bt y pe B i na r y _Va l ue i s I n t e ge r r an g e 0 . .1 ;2 t a s k t ype s e m aphore ( Va l ue :3 B in a ry _Va lu e : = 0 ) i s4 e nt r y P ;5 e nt r y V;6 end semaphore ;

    27

  • 8/13/2019 Real Time System and Programming Langauges

    28/49

    1 t a sk b o dy s e ma p ho re i s2 begin3 loop4 select5 w he n v al ue = o ne = >6 a c c ep t P ;7 v al u e : = 0 ;8 or9 a c c ep t V;

    10 v al u e : = 1 ;11 or12 terminate ;

    13 e nd s e l ec t ;14 e nd l oop ;15 end semaphore ;

    If task is aborted, the semaphore is deadlocked.

    Question 6.4A tasking implementation might be more expensive but it allows thesemaphore to timeout on the signal operation and release it for othertasks.

    Question 6.5

    Assuming a task which implements a sempahore.For mutual exclusion:

    mutex : semaphore;For signalling processes suspended:

    next : semaphore;For each condition:

    x_cond : semaphore;

    next and x_cond must be initialised sonext.P;x_cond.P;

    For each procedure: mutex.P;

    body;if next.Pcount > 0 then

    next.V;else

    mutex.Vend if

    For each wait on condition xif next.waitcount > 0 then

    next.V;else

    mutex.V;x_cond.P;

    For each signal on condition xif x_cond.P > 0 then

    28

  • 8/13/2019 Real Time System and Programming Langauges

    29/49

    x_cond.V;next.P;

    end if ;

    This will not work because of count; we must keep explicit count toavoid the race condition.

    Question 6.7

    1 t a s k ENTRY_DETECTOR;2 t a s k EXI T_DETECTOR;3 t a s k LI GHTS_CONTROLLER i s4 e n t ry CARS_LEFT ( X : NATURAL ) ;5 e n t ry CARS_ARRI VED( X : NATURAL) ;6 e nd LI GHTS_CONTROLLER;7

    8 t a sk b o dy E N T RY _ DE T E CTO R i s9 T MP : N AT U RA L ;

    10 begin11 loop12 TM P : = CARS_ENTERED;13 i f TMP > 0 t he n14 LIGHTS_CONTROLLER.CARS_ARRIVED(TMP);15 e nd i f ;16 d e l ay 10 .0;17 e nd l oop ;18

    e nd ENTRY_DETECTOR;

    1 t a sk b o dy E X I T_ D ET E C TO R i s2 T MP : N AT U RA L ;3 begin4 loop5 TM P : = CARS_EXITED ;6 i f TMP > 0 t he n7 LIGHTS_CONTROLLER. CARS_LEFT (TMP);8 e nd i f ;9 d e l ay 10 .0;

    10 e nd l oop ;11 e nd EXI T_DETECTOR;

    1 t a s k body LI GHTS_CONTROLLER i s2 N : c on s ta n t N ATU R AL := ? ?;3 - - v a ri e s a c c or d i ng t o t u nn e l4 C U RR E NT : N AT U RA L : = 0 ;5 begin6 loop7 select8 a c ce p t C A RS _ A RR I V ED ( X : N ATU R AL ) d o9 C UR R EN T : = C UR R EN T + X ;

    10 e nd CARS_ARRI VED;11 i f C UR RE NT > N t he n12 SET_LIGHTS (RED );13 e nd i f ;14 or15 a c c ep t CARS_LEFT ( X : NATURAL) do16 C UR R EN T : = C U RR E NT - X ;

    29

  • 8/13/2019 Real Time System and Programming Langauges

    30/49

    17 end CARS_LEFT ;18 i f C UR RE NT < N t he n19 SET_LIGHTS (GREEN);20 e nd i f ;21 o r t e rmina te ;22 e nd s e le c t ;23 e nd l oop ;24 e nd LI GHT_CONTROLLER;

    Question 6.8

    1 w i t h Ada .Te x t_ I O; u s e Ada .Te x t _ IO;2 w i t h Ada .Exc ep t i ons ; u s e Ada . e xce p t ions ;3 w i t h Ada .Num e ri c s .Di s c r e t e _ Ra ndom ;4 p r oce dur e s m oke r s i s5

    6

    7 t yp e N EE D is ( T_ P, T_ M , M_ P ) ;8 p a c ka ge Sm ok i ng_ i o i s ne w Enume r a t i on_ I O( NEED) ;9 p a c ka ge r a ndom _i ng r e d i en t s i s

    10 n e w Ada .Nume r i cs .Di s c r e t e _ ra ndom ( Ne e d );11

    12 t as k t yp e S m ok e r ( M Y_ N EE D S : N E ED ) ;13

    14 t as k A GE N T i s15 e n tr y G IV E _ MAT C HE S ( N : N EE D ; O K : ou t B OO L EA N ) ;16 e n tr y G I VE _ PA PE R ( N : N EE D ; O K : o ut B O O LE A N ) ;17 e n tr y G IV E _ TO B A CC O ( N : N EE D ; O K : ou t B OO L EA N ) ;18 e n t ry CI GARETTE_FI NI SHED;19 e nd AGENT;20

    21 t as k bo d y S m ok e r i s22 G OT : B O OL E AN ;23 begin24 Smoking_io .put (My_Need s ) ;25 loop26

    27 G OT : = FAL S E ;28

    29 c a s e M y_Ne e ds i s30 w h en T _P = >31 w h il e n ot G OT l oo p32 AGENT.GIVE_TOBACCO (MY_NEEDS , GOT) ;33 e nd l o op ;34 AGENT.GIVE_PAPER (MY_NEEDS, GOT) ;35 w h en T _M = >36 w h il e n ot G OT l oo p37 AGENT.GIVE_TOBACCO (MY_NEEDS , GOT) ;38 e nd l o op ;39 AGENT.GIVE_Ma tches(MY_NEEDS , GOT) ;40 w h en M _P = >41 w h il e n ot G OT l oo p42 AGENT.GIVE_Matches (MY_NEEDS , GOT) ;43 e nd l o op ;44 AGENT.GIVE_PAPER (MY_NEEDS, GOT) ;45 e nd c a s e ;46 i f n ot G OT th en r a is e P R O GR A M _E R RO R ; e nd i f ;

    30

  • 8/13/2019 Real Time System and Programming Langauges

    31/49

    47 - - m a ke a nd s m ok e c i g ar e t te48 Smoking_io .put ( My_Needs ) ; put_ l ine(" Smoking!") ;49 d e l ay 1 .0 ;50 AGENT.CIGARETTE_FINISHED;51 e nd l oop ;52 exception53 w h en e : o t he r s = >54 put (Except ion_Name(e) ) ;55 p ut ( " e xc e pt i on c a ug h t i n " ) ;56 Smoking_io .put ( My_Needs ) ;put_ l ine(" smoker") ;57 e nd Sm oke r ;58

    59 T P : S mo k er ( T _ P );60 T M : S mo k er ( T _ M );61 M P: Sm oke r ( M _P) ;62

    63 t as k b od y A G EN T is64 T_AVAILABLE , M_AVAILABLE ,65 P_AVAI LABLE : Boo le a n ;66 ALLOCATED_T , ALLOCATED_P ,67 ALLOCATED_M : BOOLEAN;68 Ge n : ra ndom _i ng r e d i e nt s . ge ne r at o r ;69 I ng re d i en t s : Ne ed ;70 begin71 r andom_ingredient s . rese t (gen) ;72 loop73 - - c ho s e t w o i te m s r a nd o m ly a n d s e t74 - - T_AVAILABLE , M _AVAI LABLE , P_AVAI LABLE to75 - - T R UE o r FA LS E c o r re s p on d in g l y 76 I ng re d ie n t s : = r a ndom _i ng r e d i en t s . r a ndom ( Ge n) ;77 c a s e I ng re d i en t s i s78 w h en T _P = >79 T_AVAI LABLE : = Tr ue ;80 P_AVAI LABLE : = Tr ue ;81 M _AVAI LABLE : = Fa l se ;82 p ut ( " A g en t h as " ) ;83 w h en T _M = >84 T_AVAI LABLE : = Tr ue ;85 M _AVAI LABLE : = Tr ue ;86 P_AVAI LABLE : = Fa l se ;87 w h en M _P = >88 M _AVAI LABLE : = Tr ue ;89 P_AVAI LABLE : = Tr ue ;90 T_AVAI LABLE : = Fa l se ;91 e nd c a s e ;92 put ( "Agent has " ) ; Smoking_io .put ( Ingredient s ) ;93 pu t_ l i ne ( " f or s m oke r s " ) ;94 ALLOCATED_T : = FALSE;95 ALLOCATED_P : = FALSE;96 ALLOCATED_M : = FALSE;97 loop98 select99 w h en T _AVAI L AB L E a nd n ot A L LO C AT E D_ T = >

    100 a c ce p t G I V E_ TO BA C CO ( N : N E ED ;101 O K : o ut B OO LE AN ) d o102 i f ( A ll oc at ed _ M a nd N = T _M ) o r103 ( A ll oc at ed _ P a nd N = T _P ) o r

    31

  • 8/13/2019 Real Time System and Programming Langauges

    32/49

    104 ( M _AVA IL AB L E a nd N = T _M ) o r105 ( P _ AVA IL AB L E a nd N = T _P ) t h en106 O K : = T RU E ;107 ALLOCATED_T : = TRUE;108 else109 O K : = FAL S E ;110 e nd i f ;111 i f O K t he n112 p ut ( " A g en t : g i ve n o ut To ba c co t o " ) ;113 Sm oki ng_i o . pu t ( N) ; pu t_ l i ne ( " Sm oke r " ) ;114 else115 p ut ( " A g en t : r e fu s in g To ba cc o t o " ) ;

    116 Sm oki ng_i o . pu t ( N) ; pu t_ l i ne ( " Sm oke r " ) ;117 e nd i f ;118 e nd GI VE_TOBACCO;119 or120 w h en M _AVAI L AB L E a nd n ot A L LO C AT E D_ M = >121 a c ce p t G I V E_ M ATC H ES ( N : N E ED ;122 O K : o ut B OO LE AN ) d o123 i f ( A ll oc at ed _ T a nd N = T _M ) o r124 ( A ll oc at ed _ P a nd N = M _P ) o r125 ( T _AVA IL AB L E a nd N = T _M ) o r126 ( P _ AVA IL AB L E a nd N = M _P ) t h en127 O K : = T RU E ;128 ALLOCATED_M : = TRUE;129 else130 O K : = FAL S E ;131 e nd i f ;132 i f O K t he n133 p ut ( " A g en t : g i ve n o ut M a tc h es t o " ) ;134 Sm oki ng_i o . pu t ( N) ; pu t_ l i ne ( " Sm oke r " ) ;135 else136 p ut ( " A g en t : r e fu s in g M a tc he s t o " ) ;137 Sm oki ng_i o . pu t ( N) ; pu t_ l i ne ( " Sm oke r " ) ;138 e nd i f ;139 e nd GI VE_M ATCHES;140 or141 w h en P _AVAI L AB L E a nd n ot A L LO C AT E D_ P = >142 a c c ep t GI VE_PAPER ( N : NEED;143 O K : o ut B OO LE AN ) d o144 i f ( A ll oc at ed _ M a nd N = M _P ) o r145 ( A ll oc at ed _ T a nd N = T _P ) o r146 ( M _AVA IL AB L E a nd N = M _P ) o r147 ( T_ AVAI LA BL E a nd N = T_P ) t he n148 O K : = T RU E ;149 ALLOCATED_P : = TRUE;150 else151 O K : = FAL S E ;152 e nd i f ;153 i f O K t he n154 p ut ( " A g en t : g i ve n o ut P a pe r t o " ) ;155 Sm oki ng_i o . pu t ( N) ; pu t_ l i ne ( " Sm oke r " ) ;156 else157 p ut ( " A g en t : r e fu s in g P a pe r t o " ) ;158 Sm oki ng_i o . pu t ( N) ; pu t_ l i ne ( " Sm oke r " ) ;159 e nd i f ;160 end GIVE_PAPER ;

    32

  • 8/13/2019 Real Time System and Programming Langauges

    33/49

    161 e nd s e l ec t ;162 i f ( ALLOCATED_P a nd ALLOCATED_T ) o r163 ( ALLOCATED_M a nd ALLOCATED_T ) o r164 ( ALLOCATED_P a nd ALLOCATED_M ) t he n165 a c c ep t C i ga r e t te _F i n i she d ;166 ex i t ;167 e nd i f ;168 e nd l o op ;169 e nd l oop ;170 exception171 w h en e : o t he r s = >172 put (Except ion_Name(e) ) ;

    173 pu t_ l i ne ( " e xc ep t ion c a ugh t i n Age nt " ) ;174 e nd AGENT;175 begin176 nul l ;177 e nd s m oke r s ;

    Question 6.9

    1 t a sk b o dy S E RV E R i s2 t yp e S ERVI CE i s ( A , B , C );3 n ex t : SE RV IC E : = A ;4 begin5 loop6 select7 w he n N EX T = A or8 ( n e xt = B a nd S E RV I CE _ B c o un t = 09 a nd SERVI CE_C c ount = 0 ) o r

    10 ( n e xt = C a nd S E RV I CE _ C c o un t = 0 ) = >11 a c ce p t S ERV IC E _A d o n ex t : = B ; e nd ;12 or13 w he n N EX T = B or14 ( n e xt = C a nd S E RV I CE _ A c o un t = 015 a nd SERVI CE_C c ount = 0 ) o r16 ( n e xt = A a nd S E RV I CE _ A c o un t = 0 ) = >17 a c ce p t S ERV IC E _B d o n ex t : = C ; e nd ;

    1 or2 w he n N EX T = C or3 ( n e xt = A a nd S E RV I CE _ A c o un t = 04 a nd SERVI CE_B c oun t = 0 ) o r5 ( n e xt = B a nd S E RV I CE _ B c o un t = 0 ) = >6 a c ce p t S E RV I CE _ C d o n ex t : = A ; e nd ;7 or8 terminate ;9 e nd s e l ec t ;

    10 e nd l oop ;11 e nd SERVER;

    Question 6.10(1) If exception A is raised it is trapped inside the rendezvous and thereforethe only message to appear is A trapped in sync.

    (2) If exception B is raised it is trapped inside the rendezvous butthen re-raised. This will propagate the exception to task ONE where it

    33

  • 8/13/2019 Real Time System and Programming Langauges

    34/49

    will be trapped and C raised but unhandled (note the exception doesntpropagate to main). The exception will also propagate to block Z is taskTWO where it will be handled, the handler however raises exception Cwhich is handled by block Y. The following will therefore be printed: Btrapped in sync, B trapped in block Z, C trapped in Y and Btrapped in one

    (3) If exception C is raised it is trapped inside the rendezvous. Thehandler then raises D which is propagated the task ONE and block Z.Block Z catches D with when others and then raises C which is trappedby block Ys when others. The following will therefore be printed: Ctrapped in sync, others trapped in Z, C trapped in Y and C trappedin one.

    (4) If exception D is raised it is not trapped by sync and thereforepropagates to ONE. Block Z catches D with when others and then raisesC which is trapped by block Ys when others. The following will thereforebe printed: others trapped in Z, C trapped in Y and D trapped inone.

    Question 7.8Fragment 1

    Case (1): Flag = ACase (2): Flag = B

    Case (3): Flag = ACase (4): Flag = AFragment 2Case (1): Flag = ACase (2): Flag = BCase (3): Flag = BCase (4): Flag = BFragment 3Case (1): Flag = ACase (2): Flag = BCase (3): Flag = ACase (4): Flag = AFragment 4Case (1): Flag = BCase (2): Flag = ACase (3): Flag = BCase (4): Flag = A

    1 Question 7.9

    1 p r o te c te d Con tr o l le r i s2 e n t ry S t op ( At_Loca t i on : ou t Ar r ay_Bounds );3 p r oce du re Found ( At _Loc a t ion : i n Ar r a y_Bounds ) ;4 pr ivate5 Found_At : Ar r a y_Bounds ;6 F o un d _ St r i ng : B oo le a n : = Fa l se ;

    34

  • 8/13/2019 Real Time System and Programming Langauges

    35/49

    7 end Cont ro l le r ;8

    9 p r o te c te d body Con t ro l l er i s10 e n t ry S t op ( At_Loca t i on : ou t Ar r ay_Bounds )11 whe n Found_St r i ng i s12 begin13 A t _Loc a ti on : = Found_At ;14 e nd S t op ;15

    16 p r oce du re Found ( At _Loca t i on : i n Ar r a y_Bounds ) i s17 begin18 Found_At : = At _Loc a ti on ;

    19 Found_St r i ng : = Tr ue ;20 e nd Found ;21 end Cont ro l le r ;22

    23 t a sk b o dy S e ar c he r i s24 F ou n d : B oo le a n := f al se ;25 A t _Loc : Ar r a y_Bounds ;26 S t r : Se a r c h_S t r i ng ;27 begin28 a cc e pt F i nd ( L o o ki n g_ F or : S e a r c h_ S t ri n g ) do29 S t r : = Looki ng_For ;30 e nd F i nd ;31

    32 loop33 select34 Cont ro l l er .S top( At_Location ) ;35 t h e n a bo rt36 Search_Suppor t . Search(Search_Array , Lower , Upper ,37 S tr , Found , A t _Loc ) ;38 i f F o un d t h en39 Cont ro l le r .Found( At_Loc) ;40 e nd i f ;41 e nd s e l ec t ;42 - - A t_ L oc is lo c a ti o n o f s t ri n g 43

    44 select45 a c c ep t Ge t_Re su l t ( At _Loc a t ion : ou t Ar r a y_Bounds ) do46 A t _Loc a ti on = At _Loc ;47 e nd s e l ec t ;48 or49 a c ce p t F in d ( L o ok in g _F o r : S e a rc h _S t r in g ) d o50 S t r : = Looki ng_For ;51 e nd F i nd ;52 e nd s e l ec t ;53 e nd l oop ;54 e nd Se a r c her ;

    Question 7.10There are three possible interleavings of interest.

    1. Error 1 is raised before Watch executes its raise statement. In thiscase, the then abort clause is abandoned and the message Error 1Caught printed.

    35

  • 8/13/2019 Real Time System and Programming Langauges

    36/49

    2. Error 2 is raised before Signaller calls Go and causes Error 1 tobe raised. Furthermore, the exception propagates outside the selectstatement before this happens. In this case, entry is cancelled andthe message Error 2 Caught printed.

    3. Error 2 is raised before Signaller calls Go and causes Error 1 tobe raised. However, before the exception propagates outside theselect statement, Error 1 is raised. In this case, the then abortclause is abandoned, the Error 2 exception lost and the messageError 1 Caught printed.

    Question 7.11

    #include "sig.h"

    #define MODE_A 1#define MODE_B 2#define MODE_CHANGE SIGRTMIN +1

    int mode = MODE_A;

    void change_mode(int signum, siginfo_t *data, void *extra) mode = data -> si_value.sival_int;

    int main2()

    sigset_t mask, omask, allmask;struct sigaction s, os;int local_mode;

    s.sa_flags = 0;s.sa_mask = mask;s.sa_sigaction = & change_mode;

    /* mask used to mask out mode changes whilst accessing *//* current mode */sigemptyset(&mask);sigaddset(&mask, MODE_CHANGE);

    sigaction(MODE_CHANGE, &s, &os);

    /* allmask used to mask all signals except mode change, *//* whilst waiting for the new mode */sigfillset(&allmask);sigdelset(&mask, MODE_CHANGE);

    while(1)

    sigprocmask(SIG_BLOCK, &mask, &omask);local_mode = mode;

    sigprocmask(SIG_UNBLOCK, &mask, &omask);

    36

  • 8/13/2019 Real Time System and Programming Langauges

    37/49

    /* periodic operation using mode*/

    if(local_mode != MODE_A)/* wait for mode change */sigsuspend(&allmask);

    else/* code for mode A */WAIT_NEXT_PERIOD;

    return 0;

    Question 8.1It will fail because of the execution of the select statement is not an atomicoperation. It is possible for a task calling the urgent entry to timeout orabort after the evaluation of the guards to the medium or low priorityentries but before the rendezvous is accepted. If this is the only task onthe queue then both the other entries are closed even though there is noavailable entry on the urgent entry. An entries on the medium and lowpriority queues are blocked.

    The reason you cannot extend the solution to a numeric solution witha range of 0 to 1000 is that it is not practical to enumerate all the membersof the family.

    1 s u bt y pe l ev e l i s i n te g er r an g e 0 . . 1 0 0 0;2 t a s k c on tr o l le r i s3 e n tr y s ig n _i n ( l : l e ve l )4 e n t ry r e que s t ( l e ve l ) ( d : dat a ) ;5 end cont ro l le r ;

    1 t a sk b o dy c o nt r ol le r i s2 t o t al : i n t e ge r ;3 p e nd in g : a rr a y ( l e ve l ) of i nt e ge r ;4 begin5 - - i ni t pe n di ng to 0 6 loop7 i f t ot al = 0 t he n8 a c c ep t s i gn_ i n ( l : l e vel ) do9 t ot al : = t ot al + 1 ;

    10 p en d in g ( l ) : = p e nd i ng + 1 ;11 end;12 else13 loop14 select15 a c c ep t s i gn_ i n ( l : l e ve l ) do16 t ot al : = t ot al + 1 ;17 p e nd i ng ( l ) : = p en d in g + 1 ;18 end;19 else20 ex i t ;21 e nd s e l ec t ;22 e nd l o op ;23

    37

  • 8/13/2019 Real Time System and Programming Langauges

    38/49

    24 f or i i n l ev el l oo p25 i f p en di ng ( i ) > 0 t he n26 a c ce p t ( i )( d : d at a ) d o n ul l e nd ;27 p e nd i ng ( i ) : = p en d in g - 1;28 t ot al : = t ot al - 1 ;29 ex i t ; - - l oo k f or n ew c al ls30 e nd i f ;31 e nd l o op ;32 e nd l oop ;33 end cont ro l le r ;

    Question 8.2

    pub li c c l as s Re s ou r ce M a na ger{

    p ri v at e f i na l i nt m a xR e s ou r c es = 1 0 0;p r i va t e i n t r e s ou r ce s Fr e e ;

    pub li c Re s ou r ce M a na ge r (){

    r e s ou r ce s Fr e e = m a xRe s ou r c e s ;}

    pub li c s ync h r on i z e d vo i d a l l oc a t e ( i n t s i z e )

    t h r ows I n t e ge rCons t r a in t Er r o r/ / s ee * * f or d e f in i t io n o f I n te g e rC o n st r a in t Er r o r {

    i f ( s i z e > m a xRe s ou r c e s ) t h r owne w I n t e ge rCons t r a in t Er r o r ( 1 ,m a xRe s ou r c es , s i z e );

    wh i le ( s i ze < r e s ou r c es Fr e e ) wa i t ( );r e s ou r ce s F re e = r e so u r ce s F re e - s iz e ;

    }

    pub li c s ync h r on i z e d vo i d f r e e ( i nt s i ze ){

    r e s ou r ce s F re e = r e so u r ce s F re e + s iz e ;not ifyAll () ;

    }}

    Question 8.4Assuming that tasks are queued on entries in priority order:

    1 t y pe r e q ue s t _r a ng e i s r a ng e 1 .. M A X ;2

    3 p r o te c te d r e s ou r ce _c on t r ol l e r i s4 e nt r y r eq u es t ( R : ou t r e so u rc e ;5 a m oun t : r e que s t_ r a nge ) ;6 p ro c ed u re f r ee ( R : re s ou r ce ;7 a m oun t : r e que s t_ r a nge ) ;8 pr ivate9 f r e ed : r e que s t_ r a nge : = r e que st _ r ange l a s t ;

    10 Q ue u ed : Na tu r al : = 0;

    38

  • 8/13/2019 Real Time System and Programming Langauges

    39/49

    11 .. .12 e nd r e s ou r ce _c on t r ol l e r ;

    1 p r o te c te d body r e s ou r c e _c on t r o l l e r i s2 e nt r y r eq u es t ( R : ou t r e so u rc e ;3 a m oun t : r e que s t _r a nge )4 w he n f re ed > 0 a nd5 Queue d < r e que st Count i s6 begin7 i f a mo u nt mutex);

    while(size > (R->free_resources))pthread_cond_wait(&(R->free), &(R->mutex));

    R->free_resources = R->free_resources - size;pthread_mutex_unlock(&R->mutex);

    void deallocate(int size, resource *R)pthread_mutex_lock(&R->mutex);

    R->free_resources = R->free_resources + size;pthread_cond_broadcast(&R-> free);

    pthread_mutex_unlock(&R->mutex);

    39

  • 8/13/2019 Real Time System and Programming Langauges

    40/49

    void initialize(resource *R)R->free_resources = N;/* initialise mutex and condition variables */

    Question 9.1A timing failure is dened to be the delivery of a service outside its deneddelivery interval - typically beyond some dened deadline. Often theservice is delivered late because of the time needed to construct the correct

    value for the service. If the system was designed to always deliver a valuein the correct interval then the lack of time would be manifest as anincorrect value (delivered on time). Hence timing and value failures cannotbe considered orthogonal.

    The converse to the above can also be true. A service that has failedbecause the value it delivers is incorrect may be able to deliver a correctvalue if it is given more (CPU) time; hence a correct value may be deliveredbut too late. However this is not universally true; a value failure (or error)can be due to many reasons (e.g. software error, hardware error) otherthan insufficient allocation of processor cycles.

    Question 11.1

    With the rate monotic scheduling approach, all processes are allocateda priority according to their periods. The shorter the period the higherthe priority. Process P would there have a higher priority than Q whichwould have a higher priority than S. A preemptive scheduler is used andtherefore the processes would be scheduled in the following order.

    time process total time forcurrent period

    1 P 12 Q 13 Q 24 P 15 S 16 S 27 P 18 Q 19 Q 210 P 111 S 312 S 413 P 114 Q 115 Q 216 P 117 S 518 idle

    40

  • 8/13/2019 Real Time System and Programming Langauges

    41/49

    The three processes may be scheduled using the cyclic executive ap-proach by splitting up process S into 5 equal parts S1, S2, S3, S4, and S5.(from the above rate monotonic solution). The loop is given by:loop

    P; Q; P; S1; S2;P; Q; P; S3; S4;P; Q; P; S5

    end loop;

    Question 11.2There is actually a typo in this question! Q should be the second mostimportant (after P) and with requirement of 6,1.a As P has the highest priority it will run rst for 30 ms. Then Q will

    run for 1 ms; unfortunately it has missed its rst ve deadline at6ms, 12ms, 18, 24ms and 30ms. S will run last (after 31ms) buthave missed its deadline at 25ms.

    b Utility of P is 30%. Utility of Q is 16.67%. Utility of S is 20%. Totalutility is 66.67%.

    c Two approaches could be used. If scheduling is based on earliest dead-line then the test is that total utilisation is less than 100prioritymodel is used then the rate monotonic test could be applied. It will not be assumed that the general test can be remembered by the

    student, although the lower bound value of 69% should be . As totaluntilisation is less than 69% the process set is scheduable. The ratemonotonic scheme assigns priorities in an inverse relation to periodlength.

    d For rate monotonic Q will have highest static priority, then S and thenP. The execution sequence will be:

    Process Execution Time Total TimeQ 1 1S 5 6Q 1 7P 5 12Q 1 13P 5 18

    Q 1 19P 5 24Q 1 25S 5 30Q 1 31P 5 36Q 1 37P 5 42Q 1 43P 5 48Q 1 49

    idle 1 50

    For earliest deadline the execution sequence will be the same up to therst idle time.

    41

  • 8/13/2019 Real Time System and Programming Langauges

    42/49

    Question 11.3At the minimum execution of R its utility is 10% (Total now 76.67%). Atthe maximum execution R utility is 50% (Total now 116.67%). As R is notsafety critical then it must miss its deadline (if any process must). Theearliest deadline scheme will not ensure this. The approach that shouldbe taken is to use rate monotonic scheme and to transform P so that itsperiod is less than R; ie P becomes a process with a period of 10 and arequirement of 3ms (per period). With the new scheme Q will still havethe highest static priority, then P, then S and lowest priority will go to R.The execution sequence will be:

    Process Execution Time Total TimeQ 1 1P 3 4S 2 6Q 1 7S 3 10P 2 12Q 1 13P 1 14R 4 18Q 1 19R 1 20P 3 23R 1 24

    Q 1 25S 5 30Q 1 31P 3 34R 2 36Q 1 37R 3 40P 2 42Q 1 43P 1 44R 4 48Q 1 49R 1 50

    With this scheme S gets 16ms in its rst period.

    Question 11.4The new diagram will look as follows:

    The result of inheritance is that the highest priority process now n-ishes at time 12 (rather than 16) and P1 (the next highest) now completesat time 13 (rather than 17). There are also less context switches.

    Question 11.6The rule for calculating blocking is: the maximum critical section with aceiling equal or higher than the task but used by a task with a priority

    42

  • 8/13/2019 Real Time System and Programming Langauges

    43/49

    B AA B

    A

    T

    TS

    S

    Pw

    Px

    Py

    Pz

    S

    T

    A A

    T

    A

    18

    B B

    16420

    S

    6 1412108

    lower.The rst part is to calculate the ceilings of each resource. We shall let

    the letters A,B,C,D,E stand for the tasks and their priorities.

    Resource Used By CeilingR1 B,D BR2 B,E BR3 A,C AR4 C C

    R5 C,D CR6 D,E DNote R4 is only used by one task and hence can be ignored.Applying the rule to Task A: R3 has a ceiling equal and is used by C

    (lower) hence blocking is 75ms.Task B: R1, R2 and R3 all have higher or equal ceilings and are used

    by lower; the maximum value is thus 150ms.Task C: Resources to consider, R1, R2, R5 (not R3 as it is not used

    by lower); the maximum value is thus 250ms.Task D: All ceilings are higher (or equal) but only R2 and R6 are used

    by E; the maximum value is thus 175ms.The lowest priority task cannot experience a block; hence maximum

    is 0.

    Question 11.7The task set is schedulable as

    U(P1) = 0.2U(P2) = 0.25U(P3) = 0.3Hence U = 0.75 which is below the threshold of 0.780 for thress pro-

    cesses.

    43

  • 8/13/2019 Real Time System and Programming Langauges

    44/49

    Question 11.8The task set is unschedulable because priorities have been assigned thatare not optimal. It must have period transformation applied to it. P1 istransformed to a task that has period 6 and computation time 1. RMSnow gives P1 the highest priority (ie P1 is highest and the allocation isoptimal).

    The utilisation of the task set is .1666 + .333 + .25 which is below thebound for schedulability. Hence system is OK.

    Question 11.9The key here is to note that the formulae is necessary but not sufficient.This means that if a task set passes the test it is schedulable but if it failesthe test it may or may not be scheduable. The worst phases for periodsis when they are relative primes. The given task set has one task as half the frequency of the other and hence the utilisation bound on this set isabove that predicted by the formulae.

    Question 11.13The key here is to recognise that the period of the process has to be atleast half the deadline of the event.

    Question 11.14The processes must be given priorities in rate order so C Event, E Event,B Event, A Event and D Event is the correct order.

    Utilisation for each process must be worked out:A Event 11.11%B Event 8.33%C Event 20%D Event 16.67%E Event 16.67%Giving a total of 72.78%The lower bound test of 69% would imply not schedulable. But for 5

    tasks the bound is 74the process set is schedulable

    Question 11.15To schedule optimally the priorities must be assigned by the deadlinemonotonic rule. This gives process b the highest priority, then process a ,then process c. Premptive scheduling must be used. Applying equationthe response time equation gives R b = 4, R a = 8 and R c = 29 Henceall tasks are schedulable.

    44

  • 8/13/2019 Real Time System and Programming Langauges

    45/49

    Question 11.16In any interval being considered, it is possible to calculate the number of time, K , the clock handler could have executed:

    K = R iT clk

    It is also possible to calculate the number of movements, V , there hasbeen from the delay queue to the dispatch queue:

    V =g p

    R iT g

    where p is the set of periodic tasks.If K V , we must assume, for the worst case, that each movement

    occurs on a different clock tick (and hence must be costed at CT c ). If this is not the case, a reduuced cost can be used. Hence equation 16.4becomes:

    R i = CS 1 + C i + B i

    +j hp ( i )

    R iT j

    (CS 1 + CS 2 + C j )

    +k s

    R iT kIH + R iT clk

    CT c

    + I p

    I p = if K V : V CT s

    else K CT s + ( V K ) CT m

    Question 11.18This periodic task suffers release jitter. It the worst case this is 20 mil-

    liseconds. Use equations 13.11 and 13.12 to calculate response time withthis jitter.

    Question 12.1Basically, WCET and blocking time can be wrong, sporadics can be in-voked more often that anticipated, and the application periodic processescould compute the wrong delay value. The tools may be wrong.

    RTS could handle the timing events for periodics, and check that spo-radics dont go off more often than anticipate. Watdog timers?

    Still cant really guarantee without memory rewalls.

    45

  • 8/13/2019 Real Time System and Programming Langauges

    46/49

    Question 12.2With the mode change example, a number of tasks need to have theirpriorities changed. Typically, these changes should take place atomically(that is, all changed together). To achieve this, a protected object with ahigh ceiling priority could be used. For example, in the following, a groupof N tasks can exist in one of four modes. A call of Set Mode will changethe priorities of the tasks. Each task must, however, rst call Register ,so that its identity can be held:

    1 w i t h Ada .Ta s k_ I de n ti f i c a t ion ;2 w i t h Ada .Dyna m i c _Pri o r i t i es ;3 u se Ada .Dyna m i c_Pr i o r it i e s ;4 w i t h Syst e m ;5 p a c ka ge F l i gh t _M a na ge me n t i s6 N : co ns t an t P o s it i ve : = . . .;7 t yp e Tas k _R a ng e i s r a ng e 1 .. N ;8 t ype M ode i s ( Ta xi i ng , Ta ke_Off , Cr u is i ng , La ndi ng ) ;9

    10 M ode _Pri o r i t i es : a r r ay ( Ta s k_Ra nge , M ode ) o f Sys te m .Pr i o r it y ;11 - - p ri o ri t i es a re s e t du ri n g an 12 - - i n it i al i s at i o n ph a se o f t h e p ro g r am 13

    14 t ype La bel s i s a r r ay ( Ta s k _Range ) o f15 Ada .Task_Ident i f i ca t ion .Task_Id;16

    17 p r o te c t ed M ode _Cha nge r i s

    18 p ragma Pr ior i ty(Sys tem .Pr ior i ty Las t ) ;19 p r oce du re Re g i s t er ( Na m e : Ta sk_Range ) ;20 p r oce du re Se t _M ode ( M : M ode ) ;21 pr ivate22 C u r re n t_ M o de : M od e : = Ta xi in g ;23 Ta s k_La be l s : La be l s ;24 e nd M ode _Change r ;25 e nd F l i gh t _M a na ge m en t ;

    The body of Mode Changer will be1 p r o te c te d body M ode _Cha nge r i s2 p r oce du re Re g is t er ( Na m e : Ta s k_Ra nge ) i s3 begin4 Task_Label s (Name) :=5 Ada .Task_Ident i f i ca t ion .Cur rent_Task;6 e nd Re g is t er ;7

    8 p ro c ed u re S e t_ M od e ( M : M od e ) is9 begin

    10 i f M / = C u r re n t _M o d e t he n11 C u r re n t _M o d e : = M ;12 f or T i n Tas k _R a ng e l oo p13 Se t_Pr ior i ty( Mode_Pr ior i t i es (T ,M) ,Task_Label s (T) ) ;14 e nd l o op ;15 e nd i f ;16 e nd Se t _M ode ;17 e nd M ode _Cha nge r ;

    Note that this will only work if all the tasks rst register.

    46

  • 8/13/2019 Real Time System and Programming Langauges

    47/49

    Question 14.1

    1 - - a s s u m in g S y s t em i s a l r e a dy w i th e d a nd u s ed 2

    3 He a r t _M on i t o r : c onst a n t I n t e r r rup t _ I d : = . . .. ;4

    5 w or d : c on st an t : = 2 ; - - n um be r o f s t or ag e u ni ts i n a w or d 6 B i t s_ I n _Wo r d : c on s ta n t : = 1 6 ; - - b it s i n w or k 7

    8 t y pe c sr i s n e w i n t eg e r ;9 f or Cs r S i z e u s e B i t s _ I n_Wor d ;

    10 f or Cs r Al i gnm en t u se Wor d ;11 f or Csr B i t _Or der u se Low_Or der _F i r s t ;12

    13 p r o te c te d I n t e r r up t _Ha nd le r i s14 e n t ry wa i t _hea r t _be at ;15 pr ivate16 p r oce du re Ha ndl e r ;17 p ragma At tach_Handler (Handler , hear t_moni tor ) ;18 p ragma In ter rupt_Pr ior i ty ( In te r rupt_Pr ior i ty Las t ) ;19 I n te r r up t _ Oc c ur e d : B o ol e an : = F al se ;20 e nd I n t e r r up t _Ha nd le r ;21

    22 t a s k pa t i e n t _m on i t o r ;23

    24 p r o te c te d body I n t e r r up t _Ha nd l e r i s25 p r oce du re Ha nd l e r i s

    26 begin27 I n t e r r up t _Oc c u re d : = Tr ue ;28 e nd ha ndl e r ;29

    30 e n t ry wa i t _he ar t _be a t when I n t e r r upt _Oc c u re d i s31 begin32 I n t e r r up t _Oc c u re d : = Fa l se ;33 e nd wa i t _he ar t _be a t ;34 e nd I n t e r r up t _Ha nd le ;35

    36 t a s k body pa t i e n t _m on i t o r i s37 Con t r o l_Re g_Addr : c onst a n t Addr es s : = 8##177760# ;38 e cs r : c sr ;39 f o r e cs r Addr e ss u se Con t r ol _Re g_Addr ;40 v ol ts : c sr := 5;41 begin42 loop43 select44 In te r rupt .wai t_hear t_b ea t ;45 v o lt s : = 5 ;46 or47 d e l ay 5 .0 ;48 select49 supervisor .sound_a larm ;50 else51 nul l ;52 e nd s e l ec t ;53 e c sr : = v ol t s ;54 v o lt s : = v o lt s + 1;55 e nd s e l ec t ;

    47

  • 8/13/2019 Real Time System and Programming Langauges

    48/49

  • 8/13/2019 Real Time System and Programming Langauges

    49/49

    52

    53 C u rr e n t_ C o st : I nt eg e r : = 0 ;54

    55 t as k H an d le r i s56 en t ry In te r rupt ;57 f or In t er r up t us e a t 8 #6 0 #;58 p r a gm a Ha r dwa r e_Pr i o r it y ( 6 ) ;59 - - o t he r s o l u t i ons a c c e p t a bl e60 e nd Ha ndl e r ;61

    62 t as k bo d y H a nd l er i s63 begin

    64 Sha dow.C1 : = Re g i s t r at i on_Num be r ( 1 ) ;65 Sha dow.C2 : = Re g i s t r at i on_Num be r ( 2 ) ;66 Sha dow.C3 : = Re g i s t r at i on_Num be r ( 3 ) ;67 Sha dow.C4 : = Re g i s t r at i on_Num be r ( 4 ) ;68 Sha dow.C5 : = Re g i s t r at i on_Num be r ( 5 ) ;69 Sha dow.C6 : = Re g i s t r at i on_Num be r ( 6 ) ;70 Sha dow.C7 : = Re g i s t r at i on_Num be r ( 7 ) ;71 Sha dow.C8 : = Re g i s t r at i on_Num be r ( 8 ) ;72 Sha dow.De t a i ls : = Cur r e n t _J ou r ne y ;73 Sha dow.Code : = Code ;74 S h ad o w. Go : = Yes ;75 loop76 a c c ep t I n te r r up t do77 CR: = Sha dow;78 C u rr e n t_ C o st : = C u rr e n t_ C o st + D R ;79 select80 Display_Dr iver.Put_Cos t (Cur rent_Cos t ) ;81 else82 nul l ;83 e nd s e le c t ;84 end In te r rupt ;85 e nd l oop ;86 e nd Ha ndl e r ;87

    88 e nd M ot o r way_Cha rges ;