You are on page 1of 87

UNIT 5

Real Time Operating


System
Software architectures
• Round-robin

• Round-robin with interrupts

• Function-queue-scheduling

• Real-time operating system(RTOS)


• Factor that determines which architecture will be most
appropriate is
– How much control one must have over system response
• How hard it will be to achieve a good response
– Depends on absolute response time requirements
– Speed of processor
Round Robin (RR)
• Very common base policy.
• Simplest architecture
• No interrupts
• The main loop checks each of the I/O devices in turn and services any that needs
service
• A typical time slice today is between 10-100 milliseconds, with a context switch time
of 0.1 to 1 millisecond.
RR Contd…
Void main(void)
{
while(true)
{
if ( I/O device A needs service)
• No interrupts
{ • No shared data
Take care of I/O device A
Handle data to or from I/O device A • No latency concerns
}
if ( I/O device B needs service)
{
Take care of I/O device B Ex.: Digital multimeter
}
Handle data to or from I/O device B Digital watches
…. Microwave oven
}
}
Contd…

Advantages
• Very simple
• No shared variables
Disadvantages
• Possible long response time:
• might not meet requirements
• might feel sluggish
• No priority mechanism
• Fragile: hard to extend
Round-Robin with Interrupts
• Short Interrupt routines to handle the urgent needs of the
hardware and set flags
• The main loop checks the flags and performs the actual
needed processing
• Different devices can be assigned to different levels of
priority interrupts
.
_oi _ ma1 (voi _
{
while (TR - )
{
if (f eviceA)
(
f eviceA FALs ~:
!! andle data to or From 110 Dev·ce A
)
1f ( f - e - 1 c eB )
{ voi = interr . t vHan : le .eviceA (voi _- )

f ev1ce8 - FALSE; JI Take care or 110 Device A


!J - and le data to or From 110 Devjce B
f Devi ceA - TRUE;
)
.
.
voi :- ii nterr . t vHan ·- l eDevii ceB ( voii _- )
) {
!! Take care of 110 Oev1ce B
fDev1ceB - TRUE:


voi: i nterr . t vHan le ev1 ceZ ( voi )


{
JJ Take care or 110 Device Z
fDeviceZ - TRUE;
Contd…
Advantages
• Built-in priority scheme
• Immediate response to external Interrupts
Disadvantages
• Shared variables must be handled
• Inflexible priority scheme
• Long worst-case response time
Function-Queue Scheduling

• A queue is maintained with functions to call

• Interrupt routines add functions to the queue

• The main loop calls functions from the queue

• Priority handling can be accomplished by making the queue


a priority queue
Contd…
void interrupt HandleDeviceA (void)
{
Take care of I/O device A, Put function_A on queue of function pointers
}
void interrupt HandleDeviceB (void)
{
Take care of I/O device B, Put function_B on queue of function pointers
}

void main (void)


{
while (TRUE)
{
while (!!Queue of function pointer is empty)
Call first function on queue
}
}

void function_A (void)


{
Handle actions required by device A
}
Contd…
Advantages
• Flexible priority scheme
• Improved response time for high priority processes
Disadvantages
• Low priority processes may be starved
• Long low priority process may cause slow response for higher
priority processes
Real-Time Operating Systems

• Short Interrupt routines to handle the urgent needs of the


hardware and set signals (not flags)
• No processing loop
• The operating systems selects what runs next based on a
flexible priority scheme
• Any function can be interrupted
Contd…
• Signaling between ISR & task code handled by RTOS
(Not need to use shared variables)
• Code inside RTOS decides which of the task code functions should run
• RTOS suspend one task code subroutine in the middle of its processing
(Control task code response as well as interrupt routine response)
• Widely available for purchase
• System’s response is stable, as when you change the code
• Zero worst case wait for the highest-priority
• RTOS itself uses a certain amount of processing time
Contd…
void interrupt Handle DeviceA (void)
{
Take care of I/O device A, Set Signal X
}
void interrupt Handle DeviceB (void)
{
Take care of I/O device B, Set Signal Y
}

void Task1 (void)


{
while (TRUE)
{
Wait for Signal X , Handle data to or from I/O device A
}
}
void Task2 (void)
{
while (TRUE)
{
Wait for Signal Y , Handle data to or from I/O device B
}
}
Contd…
Advantages
• No shared variables to worry about
• Very flexible priority scheme
• Very short response time for high priority processes
• Stable against system modifications
• Readily available packaged operating system software with
debugging tools
Disadvantages
• Complex operating system code
• Overhead for operating system code
Contd…

Round-robin RR with interrupts RTOS

High priority
Everything Device A ISR Device A ISR
Device B ISR Device B ISR
Device C ISR Device C ISR
Device D ISR Device D ISR
Device E ISR Task Code 1
Device F ISR Task Code 2
Low priority Device G ISR Task Code 3
All task Code Task Code 4
Summary
Worst Response Time for Stability of response when the
Priority available task code code changes Simplicity

Round robin None Sum of all task code Poor Very Simple

ISR-priority order All Total of execution time Must deal with data shared
Round robin Task codes-same Good for ISR between ISR and Task code
for all task code
With Interrupt Poor for task code

Function Queue ISR and Task code - Execution time for the Must deal with shared data and
scheduling priority order longest function must write function queue code
Relatively good

Real-time operating ISR and Task code -


system priority order
Zero Very good Most complex
UNIT-5
Software Architectures
• Round-robin

• Round-robin with interrupts

• Function-queue-scheduling

• Real-time operating system(RTOS)


Criteria of Scheduling Algorithms
• CPU Utilization: The percentage of time that the CPU is busy.

• Throughput: The number of processes completing in a unit of time.

• Turn around time: The length of time it takes to run a process from
initialization to termination, including all the waiting time.

• Waiting time: The total amount of time that a process is in the ready
queue.

• Response time: The time between when a process is ready to run and
its next I/O request.
Function-Queue Scheduling

• A queue is maintained with functions to call

• Interrupt routines add functions to the queue

• The main loop calls functions from the queue

• Priority handling can be accomplished by


making the queue a priority queue
Contd…
void interrupt HandleDeviceA (void)
{
Take care of I/O device A, Put function_A on queue of function pointers
}
void interrupt HandleDeviceB (void)
{
Take care of I/O device B, Put function_B on queue of function pointers
}

void main (void)


{
while (TRUE)
{
while (Queue of function pointer is empty)
Call first function on queue
}
}

void function_A (void)


{
Handle actions required by device A
}
Contd…
Advantages
 Flexible priority scheme
 Improved response time for high priority processes
Disadvantages
 Low priority processes may be starved
 Long low priority process may cause slow response for
higher priority processes
Real-Time Operating Systems

• Short Interrupt routines to handle the urgent


needs of the hardware and set signals (not flags)

• No processing loop

• The operating systems selects what runs next


based on a flexible priority scheme

• Any function can be interrupted


Contd…
 Signaling between ISR & task code handled by RTOS
(Not need to use shared variables)
 Code inside RTOS decides which of the task code functions
should run
 RTOS suspend one task code subroutine in the middle of its
processing
(Control task code response as well as interrupt routine
response)
 Widely available for purchase
 System’s response is stable, as when you change the code
 Zero worst case wait for the highest-priority
 RTOS itself uses a certain amount of processing time
Contd…
void interrupt Handle DeviceA (void)
{
Take care of I/O device A, Set Signal X
}
void interrupt Handle DeviceB (void)
{
Take care of I/O device B, Set Signal Y
}

void Task1 (void)


{
while (TRUE)
{
Wait for Signal X , Handle data to or from I/O device A
}
}
void Task2 (void)
{
while (TRUE)
{
Wait for Signal Y , Handle data to or from I/O device B
}
}
Contd…
Advantages
• No shared variables to worry about
• Very flexible priority scheme
• Very short response time for high priority
processes
• Stable against system modifications
• Readily available packaged operating system
software with debugging tools
Disadvantages
• Complex operating system code
• Overhead for operating system code
Contd…

Round-robin RR with interrupts RTOS

High priority
Everything Device A ISR Device A ISR
Device B ISR Device B ISR
Device C ISR Device C ISR
Device D ISR Device D ISR
Device E ISR Task Code 1
Device F ISR Task Code 2
Low priority Device G ISR Task Code 3
All task Code Task Code 4
Summary
Worst Response Time Stability of response when
Priority for task code the code changes Simplicity
available

Sum of all task


Round robin None Poor Very Simple
code

ISR-priority order Must deal with data


Total of execution time
Round robin All Task codes-same Good for ISR shared between ISR and
for all task code
Task code
With Interrupt Poor for task code

Must deal with shared data


Function Queue ISR and Task code - Execution time for the
and must write function
scheduling priority order longest function Relatively good queue code

Real-time ISR and Task code -


operating priority order
system Zero Very good Most complex
INTRODUCTION TO
RTOS AND
ITS FEATURES
What is RTOS ?

.
lrntertas.k
• Real-time systems
are those systems in
which
the correctness of
D,namic the system
l/Tummy Manage- depends not only on
the logical result of
[im ·rs
Allio. ment
computation, but
also on the time at
which the results are
produced.
Snper,mo:r • Real Time Operating Systems .

I
Time embedded system (RTOS)

• RTOS is key to many embedded systems and provides a platform


to build applications.
• All embedded systems are not designed with RTOS.
• Embedded systems with relatively simple/small hardware/code
might not require an RTOS.
• Embedded systems with moderate-to-large software applications
require some form of scheduling, and hence RTOS.
How are they different ?

• TASK SCHEDULING
• DETERMINISM
• PREEMPTIVE KERNEL
• PRIORITY INVERSION
• USAGE
Rlli\,~Z: llllliJ!l15MifflWJIH&&fftWJ!Ait1iSCT7JSMII

HARD REAL TIME CLASSIFICATIO


FIRM REAL TIME N
of RTOS
SOFT REAL TIME
WHAT EXACTLY ?

• Hard real-time: Degree of tolerance for missed


deadlines is negligible. A missed deadline can
result in catastrophic failure of the system
• Firm real-time: Missing a deadly ne might result
in an unacceptable quality reduction but may not
lead to failure of the complete system
• Soft real-time: Deadlines may be missed
occasionally, but system doesn’t fail and also,
system quality is acceptable
I
• Multithreading and
preemptability
• Thread Priority
• Inter Task
Features Communication &
Synchronization
of • Priority Inheritance
rtos • Short Latencies
• Task switching latency
• Interrupt latency
• Interrupt dispatch latency
Multithreading
and
preemptability

• The scheduler
should be able
to preempt any
task in the
system and
allocate the
resource to the
thread that
needs it most
even at peak
load.
I
Thread
priority
PRIORITY

60 TH1
--•'=T=~_; · TH1

• • • • All tasks are


assigned
priority level to
TH2 TH2
facilitate pre-
30

20

•• TH3 .
• • H3
emption.The
highest priority

I
• I
TIME
task that is
ready to run
will be the task
REQUEST - EXIT PROCESSOR

I t
that will be
ACQUIRE PROMOTE

I ♦
running.
RELEASE DEMOTE
• Inter Task Communication &
Synchronization - Multiple tasks
pass information among each other
in a timely fashion and ensuring
data integrity
• Priority Inheritance - RTOS should
have large number of priority levels
& should prevent priority inversion
using priority inheritance.

I
• Interrupt dispatch latency:
Short Latencies - The The time from the last
latencies are short and instruction in the interrupt
predefined. handler to the next task
scheduled to run.

• Interrupt latency: The time


• Task switching latency: The
elapsed between execution
time needed to save the
of the last instruction of the
context of a currently
interrupted task and the first
executing task and switching
instruction in the interrupt
to another task.
handler.
• RTOS Architecture -
Kernel
• RTOS Architecture
• For simpler
applications, RTOS is
usually a kernel but as
complexity increases,
various modules like
networking protocol
stacks debugging
facilities, device I/Os
are includes in
addition to the kernel.

I
Vulnerabilites

I
Unit-5

Inter process communication


Inter-Task co1
mmunication &,
Synchronization
• Tbese sei-vi.ces makes it possible to pass infonnation from one task to another
without infonnation ever being damaged.

• Makes it po · ible or ta k to coordinate & productiv _ly cooperate with _ach


oth _r.

• The most importa nt communication betwe en tasks in an OS is the passin,g of data


1

f1
r om one task to a nothe1r.

• l f m,e ssages ,a re sent more quickly t han they can be handled, t he OS provides
message queues fo,r holldi ng the messages until they c,an be processed.

Messag Message
Producer Task Receiver Task
It is, s.ometime,s ne,ce,ssary for a task or an SR to communicate ·ntormat''on to another
task. This information transfer is calle,d intertask communicatio.n. Information 1
m ay be
communicat,e d between tasks ·n two, ways::through global data or by sending mes,sages,.

Wh,en using gllolba l variables, e,ach task or ISR. rm ust ensU1 re that it has exclus ive, a1ccess t ,o
t he va r iables.

If an ISR is involved, the on ly way to ,ens11.1 n;2 excl usiive access t o t he ,c ommon variable,s is to
disable interrupts.

If t wo tasks are shar ing data each can gaiin excllusi'v,e access to t h e vari'abl,es by usi ng e'i ther
disabling/enablii ng inter rupts or th rough a semaphore (as we have s,een). Note that a task
earn only commun icate information to an ISIR by using global va riablles.

A ta sk is n,ot aware when a global varia b le is changed by an, ISR un less t he ISR sign,als t he
task by usi ng a semaphore or by having, the task regu la rly polll t he contents of t he va ri ab le.

To correct this situation, you shou d cons,i der using either a


m,essage mailbox or a message queue.
Message Ma ii boxe·s.

PENO ►
1

Messages can be· se·nt to a task through kernel services.

A Mes.sage Mailbox, a l so called a message exchang,e , is typicallly a pointer s·ze· variable .

Through a service provided by the kernel, a task or an ISR can deposit a message (the
pointe·r) ·nto this mailbox. Simila1rly, one or moire tasks can l"leceive mess.a ges through a
se·rvice p1rovided by the kernel.

Both the sending task and receiving task will agree as to what the po·nter is actually
pointing to.
Kerne services are typically provided to:
a) Initialize the contents of a m1ailbox . The ma 'illbox may or may not initially contain a
me,ssag e.
1

b) Deposit a m,essa ge into the ma iIbox (POST).


c) Wait for a messaige to be deposit,ed into t he maiilbox (PEND).
di) Get a messa,se from a mailbox, if one is present, but not suspe·nd the cal le r if t he
mai lbox is empty (ACCEPT) . If the ma ilbox conta ins a m essage, t he m essage is extracted
1

from the mai lbox.

A retu rn code is used t o notify the callller about the outcome of t he ca ll.

µC/OS- 11 provides fi ve services to access


ma ill boxes :
OSM boxOreate(),
OSMboxPend(),
OSM boxPost(),
OSMboxAcce·p,t() and
OSMboxQuery().
--air-ox
Q1SMJo10 ~-P,o _ t (.)
C,1S ;,o=- _CC -pt () _ essag1e,
Message queue

message, queues and mailboxes are soiftware-engine,ering components used for inter
process comm un ication, or for inter-thread com 1
m1uniication within t he sam,e process.
They use a queue for m,essaging - the passing of contro,I or of content. Group
communkatio,n systems provide similar kinds of functiona lity.

A message, queue, is used to send one or more messages.to a taslk.

A message queue, is basical y an array of mailboxes.

Through a service provided by·the ker·n el, a task or an ISR can deposit a me,s.saig e (the
pointer) into a message queue ..

one or 1
m ,o re tasks can re,c eive me·s.sages thr,o ugh a service provide,d by the kernel.
~m rru ~ s PEND

ll :' II e

Kernel services are typically provided to:


a} Initialize the queue. The queue is always assumed to be empty after initialization.
b) Deposit a message into, the queue (POST).
c) Wait for a message to be depo,sit,ed into the queue {PEND).
d) Get a message from a queue, if one is present, but not suspend t he ca ller if the queue is
empty (ACCEPT).

If the queue contained a message, the message is extracted from t he queue. A return code is
use,d to notify the cal ler about the outcome of the call.
Both the sending·task and receiv·"ng task wil agri!e as to what t he pointer is actua ly
pointing to .

G1ene1rally, the first mes.s age inse·rted in the queue will be· the first mie s.s age extracted
fro the ,q1ueue ,(IFIFO).

lln addition t,o e·x tract me·s.sages in a FIFO fas ion, µC/OS -111allows a task to get messages.
Last-In-first-Out f--FO).

As w'ith the mailbox,. a1·w aiting ist is as.sociated with e·a ch mes.s age queue i case mor'le
than one task is to receive messages through the ,q ueue .

A task desiring to receive a mess.age from an empty q ue·ue wi I_ be suspended and


placed on the waiting list untilla message is rece·i ved .
The kernel ·will allow the task waiting for a1message to spec·fy a timeout . If a message is
not received be·f ore the timeout expires, the requesting taslk is made· ready-to-run and
an erroir code (indicating a time·o ut occurred) i-s returned to ·t. When a message ·s
depos.i ted into the queue, either the highest pr· ority task or the firs,t task to wait for the
message wil be given the me·ssage·.

µC/OS-11 provides sev,e n se·rvices t ,o access message que·ues:


OSQCireate·(),
OSQPend(),
OSQPost(),
OSQPostfront()J
OSQAccept(),,
OSQFllush() and
OSQQuery().
OSQC:re-a. t
1 ()
OSQ Po,s:· ·. 1()
1

OSQ,Po,s ·t Fron·t
OSQ,:F 1 us.h 1(::,
1( )

l
'Task

OSQ,Po,s 't 1( )
OSQ PO,S't P,r on't 1( )
1
e·ssage
osg,·, l US,h ()
osg,Acc,ep I- ( )
5. Pipes
Write Data
Read Data
to Pipe
)

Read Data
Write Data
from Pipe

7
/4teData
"'
Read Data
from Pipe
to Pipe
Pipes
• A pip,e is an RTOS object t hat provide simplle
communication channel used fo r unstructured data
exchange among tasks. A
• Pipes can be opened, closed, written to and read
from.
• Traditionally, a pipe is a unidirectional data exchange
faci lity.
• Data is written into the pipe as an unstructured byte
stream. Unlike m,essage queue, a pipe does not store
multiple messages but strea1 m of bytes.
• lln addition, data flow from a pipe cannot b,e
• prioritized.
Pipes
• A task can write into pipe and another task
can read the data from Pipe.
• The output of one task is passed on as in11p ut
the other task.
• Task to Task or ISR to task data transfer can
take place using pipes.
Timer Management
• Timers are used to measure the elapsed time of ev,e nts.
• The kernel has to keep track of different times.
- A particular task may need to be ,e xecuted
p,eri,o,dically, say, every lOms. A timer has to, keep
track this periodicity.
- A task may be waiting in a queue for an event to
occur. If the event does not occur for a specified time
, it has t ,o, take appropriate action.
- A task may be waiting in a queue for a shared
resource. If the resource . If the resource is not
available for a specified time, an appropriate action
has to be taken.
Timer Management
• In embedded systems, system and user tasks
are often scheduled to perform after a
specified duration.
• To providle such sclhedulling, there is a need for
a periodical interrupt to keep track of time
delays and timeout.
• Most RTOSs today offer both "relative timers"
1

that work in units of ticks, and "absolute


timers" that work with calendar date and
time.
Timer Managemen1t

• For each kind of timer, RTOSs provide ,a ''task


delay'' service, and also a ''task alert''' service
bas,e d on the signaling meclh anism (e.g. evenit
flags).
• Another timer service provided is in meeting
task deadline by cooperating w1th1task
schedulers to dete,rmine whether tasks have
met or missed their real-time deadlines.
im1er management IFunctio1
n calls
• The following are the commonly used API calls
to manage timers.
- GetTime
- SetTime
- Tim ,e Delay( in system ,c lo,c k ticks)
- Tim,e Delay· (in seco,nds)
- Reset Timer
Timer Functions
I

■ Most embedded systems must keep track of


the passage of time
■ cordless bar-code s,c anner turns itself off after
a certain numb,e r of s,e conds
■ wait for ack, re-transmit data on network
■ wait for robot arms to move
wait for motors to come up to, speed
RTOS provides a delay function
lnterru~t Handling

• An interrupt ·s a hardware mechanism used to inform the


CPU that an asynchronous event has occurr,ed .
• A fundamental challenge in RTOS design ·s supporting
interrupts and ther,eby allowing asynchronous access to
internal RTOS data structures.
• The interrupt and event handling mechani·sm of an RTOS
provides the following functions:
- Defining int,e rrupt handler
- Creation and deletion of ISR
- Referencing the state of an ISR
- Enabling and disabling of an interrupt
- Changing and referencing of an ·nterrupt mask
lnterru~t Handling
The interrupt and ,e vent h1andUng mechanism1of an
RTOS H,e lp to ,e nsure:
- Data integrity by restrictin1g interrupts from
occurring when modity·ng a data structure
Mi1
n imum 1 nterr upt latencies dlue to dlisabling of
1

interrupts when RTOS is performing cr·tic,a _


operation1s
- Faste,st possible, interrupt re,s ponses that mar e,d
the pre,emptive performaince of an RTOS
- Shortest possible interrupt completion time with
min1imum o,v erheads
Event late1
n cy

✓ The Event latency is nothing but


the "amount of time from when
t'o t1 and event occurs to when it is
r a l - im
t
sys.t m r spondls to E
serviced"
✓ In a IReal-Tim1e system, this
ime
latency should always be within
a particular limit
✓ Th·s is known as responding in
"real-time"
✓ Scheduler part of the OS t o be
configured to respond in t his
manner
Share,d memory

✓ Shared memory aUows two or more tasks to access the same


memory.

✓ When one task changes the memory, all the other tasks see the
mod1f·cat1on.

✓ Shared memory is the fastest form of Inter-Task communicat·on


because all tasks share the same pi·e,ce of memory.

✓ It also avoi·ds copying data unnecessarily.


Shared memory

✓ lo use a shared memory segment,


one task must allocate the
segment.
✓ Then each task desiring to access
ProoessA
the segment must attach the
segment.
✓· A task can make use of the shared
m1emory using the attached location
(pointer). It must use the memory
in conjunct_.on with synchronizat'" on
miethods using mutex and
semaphore.
✓ After finishing its use of the
segment, each task detaches the
segment.
✓· At som1e point, one task must >
► deallocate the segment. 1 ERTx
Unit 5
Semaphores
SRM
ISffm-W.Cll' SClfNCI:~ nDPIOUICl

What is Shared data problem?


~ ..... ~., ~J./~Ari.""'

• Problem raised in RTOS

Solution:
• Disabling interrupts
• Semaphores
• Disabling task switches
/* "Button Task"*/
void vRespondToButton (void)
{
/* High priority*/ SRM
1.·
......
__,m'IF.o
inti;
while ( TRUE)
{
11 Block until user pushes a button
i •!!ID of button pressed;
printf ("\nTIME: %08ld LEVEL: %08ld",
tankdata[1].lT1meUpdated,
tankdata[1].1TankLevel); /* "Levels
Task''*/
}
} void vCalculateTankLevels (void) /* Low priority*/
{
inti - O;
wh1le (TRUE)
{
!! Read 1eve1s of floats 1n tank i
11 Do more interminable calculation
!! Do yet more interminable ca1cu1ation

/* Store the result*/


tankdata[i].lTimeUpdated - !! Current time
/* Between these two 1nstruct1ons is a
bad place for a task switch*/
tankdata[i].lTanklevel - 11 Result of calculation

! ! Figure out which tank to do next


i - !! someth1ng new
}
)
SRM
Atomic and Critical Section
I. :ffm'IF.<il' SClf~& TKIC'10Ulm
u....,J1,a.,~ 11J./E.1(.("An.r11SU

• A part of the program is said to be atomic if it


cannot be interrupted
• The collection of lines can be atomic by adding
an interrupt disable instruction
• A set of instructions that must be atomic for
the system to work properly is called a critical
section
SRM
I. :ffm'IF.<il' SClf~& TKIC'10Ulm

Re-entrancy
u....,J1,a.,~ 11J./E.1(.("An.r11SU

• Functions that can be called by more than one task and


that will always work correctly, even if the RTOS
switches from one task to another in the middle of
executing the function= Re-entrant function
• Rules to decide if a function is re-entrant or not:
– A RF may not use variables in a non-atomic way unless
they are stored on the stack of the task that called the
function or are otherwise the private variables of that task
– A RF may not call any other functions that are not
themselves re-entrant
– A RF may not use the hardware in a non-atomic way
~
SRM
I,. m'IF.Ci
~ .. ..,.
I..
1
~
~1"'
'riilt:'iOUICl
AA-rillU

Rev ew of C Variable Storage


■ 'The foll owing code sh 0 -,s - hIch var1iables
1 1

are stored 1n memory· nsteadl 0f stack a1 nd ,c,an 1 1

he,nce cause proble1


1
ms, 1

-v oi

0 C io (. r i

' n oc 1 ;
oc·l ;
SRM
__,m......
1.· 'IF.o

■ static_int - stor,ed in m,emory and hence a s h.ared variable


■ public_int - Same ,as above. However ·n .addition, functions in other C
files can also a,ccess this variable.
■ i . ti tialized- Ditto.
■1 stri g - Sam1e
■ v a· . te - Sa.ime
■1 pa rm - stored on sit.a.ck s0 wm not cau:se a pr,oblem
1

■ parm_ptr - .stack. wm not cause problem as long as every task passes a


different value for it.
■1 st i c -1 a a . in 1memory. Onlly difference betw,een it and
stored 1
static in t is that the other can be accessed by other functions in the C
f le, whilie this variable can o,nly be acc,essed by function .
■ 1 ocal - stack.
SRM
Semaphores ......
__,m'IF.o
1.·

• Solution for shared data


problem
• Uses the pairs raise and
lower, get and give, take
and release, pend and
post, p and v, wait and
signal
• Call two RTOS function
called “Take semaphore
and Release semaphore”
SRM
struct
{
long lTa-nklevel;
long l!imeUpdated;
} tankdata[MAX~TANKS];

/* "Button Task"*/
void vRespondToButto~ (void) /* High priority*/
{
int i ;
while (TRUE) .
{
!! Block until user pushes ·~ button
i =!!Get ID of button pressed
TakeSemaphore (); ·
pri ntf ( "\nT.IME: %081 d LEVEL: %081 d",
tankdata[i].lTimeUpdated,
tankdata[i J. lTankLevel);
Re l easeSemaphore ();
}
}
/* "Levels Task"*/
. void vCalculateTanklevels (void) /* Low priority*/
{
.
inti= O;
. . .. .

while (TRUE)
{

TakeSemaphore (); .
! ! Set tankdata[j], 1TimeUpdated
!! Set tankdata[;J, lTankLevel
ReleaseSemaphore ( )': .·

..
}
}
SRM -.....

Execution flow with semaphore


I. "!ITTR"TF.
.

Code in the vc al cul a teTa n kLeve ls task. Code in the vResporidToBu tton t a sk. ·

Levels task i s calculating Button .task is blocke d


tank levels. waiting £or a button.

TakeSemaphor e ()
l
! ! Set tinkdat~[i].lT imeUpdated

The user pushes a button; the


higher-priority button task . ~
unblocks; the R..TOS swiches t a sks .
. I
. I .
I
1 !! Get ID of button
TakeSemaphor e ();

I
The semaphore i"is not available; th e .
button tas k blocks; the R..TOS
J
('This does· not return yet}
.

switch e s back.

!! Set tankdata[i],lT ankLevel


ReleaseSemap hor~ t ) ;

~ I~eleas ing the semaphore unblocks


the button task; the ' R..TOS
switches again.

(No= TakeSemaphor e returns}


printf ( .);
I
I . ReleaseSemap h~re ();
! ! Block until u s er · pushe s · a button

~
The buuo n ,as k: blocks; ,he RTOS . ·)
res u r n es the leve ls t a sk.
SRM
Multiple semaphore
I. :ffm'IF.<il' SClf~& TKIC'10Ulm
u....,J1,a.,~ 11J./E.1(.("An.r11SU

• RTOS allows multiple semaphore under same


initialization
• The semaphores should be independent of
each other
• If one task takes semaphore A, another task
can take B. similarly, if one task is waiting for
semaphore C, that task will still be clocked
even if some other task releases semaphore D
SRM
Need for Multiple semaphore
I. :ffm'IF.<il' SClf~& TKIC'10Ulm
u....,J1,a.,~ 11J./E.1(.("An.r11SU

• If lowest priority task takes a semaphore,


higher priority task gets blocked
• With different semaphores, different shared
resources can be managed
SRM
Semaphore as a Signalling Device
I. :ffm'IF.<il' SClf~& TKIC'10Ulm
u....,J1,a.,~ 11J./E.1(.("An.r11SU

• Semaphores can be used to communicate between a


task and another task or an interrupt routine
• Example – Printer
• A task stores formatted reports to be printed, into
memory
• The printer interrupts after each line, on which, the ISR
feeds it with the next line for printing
• This is done by having the task wait on a semaphore
after it has formatted a report.
• The ISR will release the semaphore once the report has
been printed and the task can start on the next report.
void vPrinterTask(void)
{
SRM ......
__,m'IF.o
1.·

BYTE by Error; /* Place for an error etur n. */


Int wMsg ;

/* Initialize the semaphore as already taken.*/


semPr inter - OSSe minit(O) :

while ( TRUE)
{
/* Wait for a m~ssage lling wha t repor t to ormat. * /
wMsg - (int) OSQPend (QP rinterTas . WAJT_ FOREVER. &by Error);

!! Format the r ,e port fn o a_ chPrint


1L7l n,e sTo a ! .! co·unt or 1"ines 1n the report

/* Pr nt the fir s t line of he epor t I


il1nesPr1n ed - O;
vHa rdwai re Pr in •rOutpu Line ( a _ chPr in" i( 1 Lines Pri nted++J) :

/ Wait for prin . job to finish. /


OSSemPend (se mP · nter, WAI T_ FOR VER &by E rror);
}
}
VO d
{
H 1L1 nes Pr nt d ~~ 1Li nesTot l )
/ Th, epo r . 1s done. R l ease t he semaph ore I
OSSemP ost (s mPr in er ) :

els,e
I* P·rint · he n xt 1 i e. •'/
1

Har d " r , ,Pr1 nte r Outp u L1 n, C. _ c:h Pri n [IL n sPr i t d · · l);
SRM
Semaphore problems
I. :ffm'IF.<il' SClf~& TKIC'10Ulm
u....,J1,a.,~ 11J./E.1(.("An.r11SU

• Forgetting to take the semaphore


• Forgetting to release the semaphore
• Taking the wrong semaphore
• Holding the semaphore for too long
• Causing a delay embrace
SRM
Deadly Embrace
int a ,b;
XID h m oreA;
.ruxID hSema horeB ;
void T sk ()
{
a sm sv (hSema ore I C, 0) ;
aJsm SV (h oreB , C, ;
a. = .
I

m ls (h 0 );
ajsrnrls (hSernapho r eB) ;
}

void ~ sk2 ()
{
aJsmrsv (hSemap oreB , C, C} ;
a sm_ V (h or I C, C} ;

b = ,•
a smr s (hSema 0 eB) ;
ajsmrls (hSemap oreA) ;
SRM
I, . m'IF.Ci
~ .. .., .
1- .
1
~
~1"'
'riilt:'iOUICl
AA-rillU

Semaphores Var ants


■1 Som1e systems aUow semaplhores that can be taken multiple time.
Taking them decrements their count and releasi1ng increments it.
They ar,e hence called countng semaphores
■ S em1aphores that can only be releas ed by the task that took them ar,e
1 1

r._·e~~~r~~ s~~~p~ho~~s. _T~oug._h_Jhe.,y_p_r~ye~t shar,ed data bugs, they


cannot be used for task ,nte r comm u n1cat1 10 n.
■1 A semaphore that deals with priority inversion is com1 mi0nly caUed a
mutex semaphore or mutex (mutuaUy exclusive).

M,ethods to P1
rotect: S,hared Data
■1 The 2 basic m1ethods are disabl"ng interrupts and using s,emaphores.
■1 A thiird 1
m,ethod is disablli g task swiitches but this has no effect on
interrupt routines .
■ Note - interrupts are not .allowed to take semaphores so they
cannot be used if the, da a is shared between the lask code and the
ISR .

You might also like