Vous êtes sur la page 1sur 81

μC/OS-II Features

 Portable : portable ANSI C, minimum micro processor


specific assembler code
 ROMable
 Scalable
 Preemptive : μC/OS-II is a fully preemptive real-time
kernel
 Multitasking : μC/OS-II can manage up to 64 tasks
 Deterministic : Execution time of all μC/OS-II functions
and service are deterministic
 Deterministic : Each task requires its own different stack
size

1
μC/OS-II Features
 Services : Mailboxes, Queues, Semaphores,
fixed-sized memory partitions, time-related functions
 Interrupt Management: Interrupt can be nested
up to 255 levels deep
 Robust and Reliable
 Shortcomings:
 μC/OS-II does not support priority inheritance.
 With μC/OS-II, all tasks must have a unique priority.
 A task, also called a thread, is a simple program that
thinks it has the CPU all to itself.

2
Tasks

 μC/OS-II can manage up to 64 tasks


 Two task are used for system use.
 The four highest priority tasks and the four
lowest priority tasks are reserved for its own
use (0, 1, 2, 3, OS_LOWEST_PRIO-3, 2, 1, 0)
 56 application tasks
 The lower the value of the priority, the higher
the priority of the task.

3
Task Control Blocks (OS_TCB)

 When a task is created, it is assigned a


 Task Control Block, OS_TCB
 OS_TCB is a data structure that is used by
 μC/OS-II to maintain the state of a task when it
is preempted
 All OS_TCB reside in RAM
 An OS_TCB is initialized when a task is created.

4
Task States

 Task (Thread) States


 DORMANT
 READY

 RUNNING

 DELAYED

 PENDING

 INTERRUPTED

5
Task Context Switch

6
Functions UCOS2.LIB

void OSInit(void);

Description
Initializes µC/OS-II data; must be called before any other
µC/OS-II functions are called.

void OSStart(void)
Description
Starts the multitasking process

INT8U OSTaskCreate(void (*task)(), void *pdata, INT16U


stk_size, INT8U prio);

Description
Creates a task to be managed by µC/OS-II.

7
OS Init exit functions UCOS2.LIB

INT8U OSTaskCreateExt (void (*task)(), void *pdata, INT8U


prio, INT16U id, INT16U stk_size, void
*pext, INT16U opt);
Description
This function is similar to OSTaskCreate() except that it allows
additional information about a task to be specified.
Tasks can either be created prior to the start of multitasking or
by a running task. A task cannot be created by an ISR.

void OS_ENTER_CRITICAL();
void OS_EXIT_CRITICAL();

Description
Enter and Exit a critical section.

8
OSSched functions UCOS2.LIB

void OSSchedLock(void);
Description
Prevents task rescheduling.

void OSSchedUnlock(void);
Description
Allow task rescheduling

9
OSSem functions UCOS2.LIB

INT16U OSSemAccept (OS_EVENT *pevent);


Description
This function checks the semaphore to see if a resource is
available or if an event occurred.
OS_EVENT *OSSemCreate (INT16U cnt);
Description
Creates a semaphore.
void OSSemPend (OS_EVENT *pevent, INT16U timeout,
INT8U *err);
Description
Waits on a semaphore

10
OSSem functions UCOS2.LIB

INT8U OSSemPost (OS_EVENT *pevent);


Description
This function signals a semaphore.

INT8U OSSemQuery (OS_EVENT *pevent, OS_SEM_DATA


*pdata);
Description
Obtains information about a semaphore.

11
OSFlag functions (OS_FLAG.C)

OS_FLAGS OSFlagAccept (OS_FLAG_GRP *pgrp,


OS_FLAGS flags, INT8U
wait_type, INT8U *err);
Description
This function is called to check the status of a combination of
bits to be set or cleared in an event flag group

OS_FLAG_GRP *OSFlagCreate (OS_FLAGS flags,


INT8U *err);
Description
This function is called to create an event flag group.

12
OSFlag functions (OS_FLAG.C)

OS_FLAG_GRP *OSFlagDel (OS_FLAG_GRP *pgrp, INT8U


opt, INT8U *err);
Description
This function deletes an event flag group and readies all tasks
pending on the event flag group.

OS_FLAGS OSFlagPend (OS_FLAG_GRP *pgrp, OS_FLAGS


flags, INT8U wait_type,INT16Utimeout,INT8U *err);
Description
This function is called to wait for a combination of bits to be
set in an event flag group.

13
OSFlag functions (OS_FLAG.C)

OS_FLAGS OSFlagPost (OS_FLAG_GRP *pgrp, OS_FLAGS


flags, INT8U opt, INT8U *err);
Description
This function is called to set or clear some bits in an event flag
group.
OS_FLAGS OSFlagQuery (OS_FLAG_GRP *pgrp,
INT8U *err);
Description
This function is used to check the value of the event flag
group.

14
OSMbox functions OS_MBOX.C

void *OSMboxAccept (OS_EVENT *pevent);

Description
OSMboxAccept() does not suspend the calling task if a
message is not available

OS_EVENT *OSMboxCreate (void *msg);

Description
Creates a message mailbox if event control blocks are available

15
OSMbox functions OS_MBOX.C

OS_EVENT *OSMboxDel (OS_EVENT *pevent,


INT8U opt, INT8U *err);
Description
This function deletes a mailbox and readies all tasks pending
on the mailbox.

void *OSMboxPend(OS_EVENT *pevent, INT16U timeout,


INT8U *err);
Description
Waits for a message to be sent to a mailbox.

16
OSMbox functions OS_MBOX.C

INT8U OSMboxPost (OS_EVENT *pevent, void


*msg);
Description
Sends a message to the specified mailbox
INT8U OSMboxPostOpt (OS_EVENT *pevent, void *msg,
INT8U opt);
Description

This function sends a message to a mailbox.


INT8U OSMboxQuery (OS_EVENT *pevent,

OS_MBOX_DATA *pdata);
Description
Obtains information about a message mailbox.

17
OSMem Functions UCOS2.LIB

OS_MEM *OSMemCreate (void *addr, INT32U nblks,


INT32U blksize, INT8U *err);
Description
Creates a fixed-sized memory partition that will be managed
by µC/OS-II.

void *OSMemGet (OS_MEM *pmem, INT8U *err);


Description
Gets a memory block from the specified partition.

18
OSMem Functions UCOS2.LIB

INT8U OSMemPut(OS_MEM *pmem, void *pblk);


Description
Returns a memory block to a partition.

INT8U OSMemQuery (OS_MEM *pmem, OS_MEM_DATA


*pdata);
Description
Determines the number of both free and used memory blocks
in a memory partition.

19
OSMutex functions OS_MUTEX.C

INT8U OSMutexAccept (OS_EVENT *pevent, INT8U *err);

Description
This function checks the mutual exclusion semaphore to
see if a resource is available.

OS_EVENT *OSMutexCreate (INT8U prio, INT8U *err);


Description
This function creates a mutual exclusion semaphore

20
OSMutex functions OS_MUTEX.C

OS_EVENT *OSMutexCreate (INT8U prio, INT8U *err);


Description
This function creates a mutual exclusion semaphore.

OS_EVENT *OSMutexDel (OS_EVENT *pevent, INT8U opt,


INT8U *err);
Description
This function deletes a mutual exclusion semaphore and
readies all tasks pending on it.

21
OSMutex functions OS_MUTEX.C

void OSMutexPend (OS_EVENT *pevent, INT16U timeout,


INT8U *err);
Description
This function waits for a mutual exclusion semaphore.

INT8U OSMutexPost (OS_EVENT *pevent);

Description
This function signals a mutual exclusion semaphore.

INT8U OSMutexQuery (OS_EVENT *pevent,


OS_MUTEX_DATA *pdata);

Description
This function obtains information about a mutex.

22
OSQ functions OS_Q.C

void *OSQAccept (OS_EVENT *pevent);


Description
Checks the queue to see if a message is available
OS_EVENT *OSQCreate (void **start, INT16U qsize);
Description
Creates a message queue if event control blocks are available
INT8U OSQQuery (OS_EVENT *pevent, OS_Q_DATA
*pdata);
Description
Obtains information about a message queue

23
OSQ functions OS_Q.C

OS_EVENT *OSQDel (OS_EVENT *pevent, INT8U


opt, INT8U *err);
Description
Deletes a message queue and readies all tasks pending on the
queue.
INT8U OSQFlush (OS_EVENT *pevent);
Description
Flushes the contents of the message queue.
INT8U OSQPostOpt (OS_EVENT *pevent, void *msg, INT8U
opt);
Description
This function sends a message to a queue.

24
OSQ functions OS_Q.C

void *OSQPend (OS_EVENT *pevent, INT16U timeout,


INT8U *err);
Description
Waits for a message to be sent to a queue.
INT8U OSQPost (OS_EVENT *pevent, void *msg);
Description
Sends a message to the specified queue.
INT8U OSQPostFront (OS_EVENT *pevent, void *msg);
Description
Sends a message to the specified queue

25
Functions
INT8U OSTaskChangePrio(INT8U oldprio, INT8U newprio);

Description
Allows a task's priority to be changed dynamically. Note that
the new priority MUST be available.

INT16U OSSetTickPerSec(INT16U TicksPerSec);


Description
Sets the amount of ticks per second

void OSStatInit(void);
Description
Determines CPU usage.

26
EXAMPLE 1
#include <dos.h> void task2()
#include "libepc.h" {
#include "os_cpu.h" while(1)
#include "os_cfg.h" {
#include "ucos_ii.h" PutCharAt('A',x,y++);
#define STK_SIZE 1024 OSTimeDly(100);
int x=0,y=0; PutCharAt('U',x,y++);
OSTimeDly(100);
void task1()
}
{
}
while(1)
{
if(x==24) x=0;
if(y==79) y=0;
PutCharAt('B',++x,y++);
OSTimeDly(100);
PutCharAt('L',x,y++);
OSTimeDly(100);
}
}
27
EXAMPLE 1

int main()
{
static OS_STK T1_STK[STK_SIZE];
static OS_STK T2_STK[STK_SIZE];

ClearScreen(0x07);
OSInit();

OSTaskCreate(task1,NULL,T1_S
TK,11);

OSTaskCreate(task2,NULL,T2_S
TK,12);

OSStart();
}

28
Example 2
#include <dos.h> void task2()
#include "libepc.h" {
#include "os_cpu.h" while(1)
#include "os_cfg.h" {
#include "ucos_ii.h" OSTimeDly(100);
#define os_stk 1024 PutCharAt('S',++x,y++);
int x=0,y=0,z=0; OSSemPend(p,0,err);
char *err; PutCharAt('M',x,y++);
OS_EVENT *p; OSSemPost(p);
void task1() OSTimeDly(100);
{ }
while(1) }
{
OSTimeDly(100);
OSSemPend(p,0,err);
PutCharAt('G',x,y++);
OSSemPost(p);
OSTimeDly(100);
}
}

29
Example 2
void task3() int main()
{ {
while(1) static OS_STK t1_stk[os_stk];
{ static OS_STK t2_stk[os_stk];
OSSemPend(p,0,err); static OS_STK t3_stk[os_stk];
OSTimeDly(100);
PutCharAt('I',x,y++); ClearScreen(0x07);
OSSemPost(p); OSInit();
PutCharAt('A',x,y++); OSTaskCreate(task1,NULL,t1_stk,11);
OSTimeDly(100); OSTaskCreate(task2,NULL,t2_stk,12);
} OSTaskCreate(task3,NULL,t3_stk,13);
} p=OSSemCreate(1);
OSStart();
}

30
1.Real-Time Systems
•Real-time systems process events.
•Events occurring on external inputs cause other events to
occur as outputs.
•Minimizing response time is usually a primary objective, or
otherwise the entire system may fail to operate properly.

Soft Real-Time System


Compute output response as fast as possible, but no
specific deadlines that must be met.

Hard Real-Time System


Output response must be computed by specified
deadline or system fails.

31
1.Real-Time Systems

• Soft Real-Time System


• Compute output response as fast as possible, but
no specific deadlines that must be met.

• Hard Real-Time System


• Output response must be computed by specified
deadline or system fails.

32
2. Multi-Tasking and Concurrency

• Most real-time systems are also embedded systems


w/several inputs and outputs and multiple events
occurring independently.
• Separating tasks simplifies programming, but requires
somehow switching back and forth among the three task
(multi-tasking).
• Concurrency is the appearance of simultaneous
execution of multiple tasks.

33
2. The build and load process for
desktop application programs.

Object Files

Compiler Executabl
e Image
File Read-

Loader
Linker
Assembler Write
Memory
(RAM)
Run-Time Library:

Boot
Operating System Image:
Process

34
2. The build and load process for
embedded application programs
Object Executabl ROM
Files e Image Read-
Image
File Write
File
Memory
(RAM)

Locator
Assemble
r Program
Linker
Initialization
Re-Entrant
Library: Read-
Only
Real-Time ROM
Memory
Kernel: "Burner"
(ROM)

35
3.INTERRUPTS
• Interrupts are signals to processor from hardware.
• The interrupt comes generally in form of signal to special pin
for interrupt.
• Processor responds by stopping the current execution and
starts to execute the ISR.
• Sometimes same interrupt is shared between two or more
devices.
• Non Maskable Interrupt cannot be disabled, generally used in
critical situations.
• Priorities can be assigned to the interrupts to resolve confilcts.
• The processor jumps to a particular address in response to an
interrupt.
• Processor does not stop in between an instruction in response
to an interrupt. Nesting of interrupts is allowed.
• Interrupts are disabled at start up.

36
3.INTERRUPTS
Static int temp[2];
Void interrupt readtemp( void ){
temp[0]=read val;
temp[1]=read val;
}
void main( void ){ SHARED
int tem0,tem1;
while(TRUE) { DATA BUG
tem0=temp[0];
tem1=temp[1];
if(tem0!=tem1) {
activate alarm
}
}
}

37
3.INTERRUPTS
SOLUTION TO SHARED DATA BUG

• Make “Critical Section” “Atomic”


• The part of code, which cannot be interrupted, is called
“Atomic”.
• The set of instructions that must be atomic for the system
to work properly is called “Critical Section”.

38
3.INTERRUPTS
Static int temp[2];
Void interrupt readtemp( void ){
temp[0]=read val;
temp[1]=read val;
}
void main( void ){
int tem0,tem1;
while(TRUE) {
disable();
tem0=temp[0];
tem1=temp[1];
enable();
if(tem0!=tem1) {
activate alarm
} } }
39
3.INTERRUPTS
• Other solutions without disabling interrupts are like
relying upon compiler to convert code to a single
instruction but is not reliable.

• Re-reading of values is another method. If both times


value is same then it may be interpreted as non-
occurrence of shared data bug.

• This method can be out done by compiler optimizations,


which reuse the pre-read value, defeating the design.

• This can be countered by using “Volatile” keyword.

40
3.INTERRUPTS

INTERRUPT LATENCY
• Defined as response time to an interrupt.
• Depends on:
• Duration for which interrupt is disabled.
• Duration of higher priority interrupts
• Time for bookkeeping.
• Time to save the context.
• Writing short and efficient code for ISR can reduce
latency.
• Make sure interrupts are not disabled for long durations.

41
3.INTERRUPTS

Static int tempa[2];


Static int tempv[2];
Static BOOL usingb=FALSE; void main( void )
Void interrupt readtemp( void ) {
{ int tem0,tem1;
if(usingb) while(TRUE)
{ {
tempa[0]=read val; if(usingb)
tempa[1]=read val; if(tempb[0]!=tempb[1]) alarm
} else
else if(tempa[0]!=tempa[1])alarm;
{ }
tempb[0]=read val; usingb=!usingb;
tempb[1]=read val; }
}
}

42
4.SOFTWARE ARCHITECTURES

ROUND-ROBIN Void main( void)


ARCHITECTURE {
Features: while( TRUE)
• No interrupts {
• Simple. if( Device A) serve A;
• Devices are polled and if( Device B) serve B;
served turn by turn. if( Device C) serve C;
• Can be used for
…….
applications like
multimeter, with absolutely …….
no time constraints if( Device Z) serve Z;
}
}

43
4.SOFTWARE ARCHITECTURES

Disadvantages:
• Worst case response is total of execution times of all
routines.
• Improvement is possible by polling faster device more
often but still very slow.
• System is fragile-add one more device and response
times change drastically.
• Absolutely no priorities.

44
4.SOFTWARE ARCHITECTURES

ROUND-ROBIN WITH INTERRUPTS


Features:
• ISRs deal with very urgent needs of hardware.
• Main routine may do the follow up.
• More control over priority.
• Shared data bug has to be taken care of.

45
4.SOFTWARE ARCHITECTURES

BOOL devicea=false;
BOOL deviceb=false; Void interrupt deviceB( void)
… {
… take care of B
BOOL devicez=false; deviceb=true;
Void interrupt deviceA( void) }
{
take care of A

devicea=true; …
} …
Void interrupt deviceZ( void)
{
take care of Z
devicez=true;
}
46
4.SOFTWARE ARCHITECTURES
void main( void)
{
while( true)
{ …
if(devicea) …
{

devicea=false;
handle data of device A if(devicez)
} {
if(deviceb) devicez=false;
{ handle data of device Z
deviceb=false;
}
handle data of device B
} }
}

47
4.SOFTWARE ARCHITECTURES
• Not simple
• All task code has same priority.
• Putting code in ISR makes device get higher priority.
• But this makes other responses slow.
• Polling of higher priority device more is possible like basic
round robin architecture.
• This technique is very fragile.
• Worst response is when interrupt happens just when
round robin passed by.

48
4.SOFTWARE ARCHITECTURES

FUNCTION QUEUE SCHEDULING


• Queue of function pointers is maintained.
• Whenever an interrupt occurs the ISR puts the pointer
pertaining to that function on queue.
• This function takes necessary action for that device.
• Main calls these pointers from queue.
• Pointers can be called in any order, so we can have
complete control over priorities.
• Worst wait for high priority function is the duration of
longest other function.
• This method may not be good enough for low priority
interrupts.

49
4.SOFTWARE ARCHITECTURES

Void interrupt deviceA( void) void main( void)


{
{
while( true)
take care of I/O A {
put function A pointer in queue while(queue is empty);
} call functions in order required
Void interrupt deviceB( void) }
}
{ void function A(void)
take care of I/O B {
put function B pointer in queue take care of A
} }
void function B(void)
{
take care of B
}

50
4.SOFTWARE ARCHITECTURES

REAL TIME OPERATING SYSTEM


• No shared data bug
• Signaling among tasks happen through RTOS.
• RTOS assigns priorities to even task code not only
interrupts.
• Any task can be suspended for higher priority one.
• Response is stable.
• Worst wait for high priority task is almost zero.
• Throughput affected and slightly more memory
consumed.

51
4.SOFTWARE ARCHITECTURES

Void interrupt deviceA( void) void task1( void)


{ {
while( true)
take care of I/O A {
set signal X wait for X
} handle I/O for A
Void interrupt deviceB( void) }
{ }
void task2( void)
take care of I/O B {
set signal Y while( true)
} {
wait for Y
handle I/O for B
}
}

52
4.1 COMPARATIVE TABLE
Architecture Priorities Worst Stability of Simplicity
response for response on
task code code change
Round-robin None Sum of all Poor very simple
task code
Round-robin Interrupts in Total time for Good for ISR Shared data
with priority and all task code poor for task problem to be
interrupts all task code code tackled
at same
priority
Function Interrupts in Time for Relatively Shared data
queue priority then longest good problem and
scheduling tasks in function function
priority queue code

RTOS Interrupts in Zero Very good Most complex


priority then
tasks in
priority 53
4.2 SELECTING ARCHITECTURE
• Select simplest system if it suits your requirements.
• If response requirements are there go for RTOS
• Combination of architectures is also possible.

54
5.RTOS BASICS
FEATURES
• Term “Real Time Operating System” and “Real Time
Kernel” are used interchangingly.
• Normal OS takes control of system as soon as it is turned
on.
• Application usually gets control of the system the RTOS
gets control.
• RTOS does not protect itself from the applications,
generally if the application passes a wrong pointer to the
RTOS, whole system crashes along with RTOS.
• Only services needed for that particular system are
included, no extra services present.

55
5.RTOS BASICS
TASKS AND TASK STATES
• Tasks are basic building blocks of a RTOS based software.
• A task is a subroutine.
• A task can be in three states:
• Running: Presently executing.
• Ready: Waiting to run if processor is available.
• Blocked: Has nothing to generally unless some external
event triggers it.
• Other states like suspend, pending, waiting, dormant etc.
are forms of either of above states.

56
5.RTOS BASICS
SCHEDULER
• Scheduler decides which task should run.
• Decision is based on priorities among unblocked tasks.
• Scheduler does not fiddle with priorities.
• A task will decide for itself that it has to enter blocked
state that means it has to run before moving to blocked
state.
• An interrupt or some other task has to pull out a task out
of blocked state.
• Scheduler takes care of shuffling between running and
blocked states.
• If all tasks are blocked system will hang.

57
5.RTOS BASICS

PREEMPTIVE AND NON-PREEMPTIVE


RTOS

• Preemptive RTOS stops a low priority task immediately


for a high priority task.
• A non-preemptive RTOS stops a task after it enters
blocked state.

58
5.RTOS BASICS
Void Buttontask( void) /*higher priority*/
{
while(true)
{
unblock on button push and respond void main( void )
}
{
}
void levels task( void) /* low priority*/ initrtos():
{ starttask(buttontask,
while(true) high);
{ starttask(levelstask,
read levels and calculate low);
}
} startrtos();
}

59
5.RTOS BASICS

• Each task will have its own context viz. stack,


register values, PC, etc.
• All other data is shared.
• Tasks are more like threads-common data area
than like processes-separate data area.

60
5.RTOS BASICS
SHARED DATA BUG REVISITIED AGAIN
Void task1( void )
{


counterrors(9);


}
Void task2( void )
{


counterrors(11);

61
5.RTOS BASICS


}
Mov r1,(errors)
static int errors; Add r1,(newerrors)
Mov (cerrors),r1
void counterrors(int newerrors) return
{
errors+=newerrors;
}

62
6.REENTERNCY
• A function, which will work correctly even when called
by, more than one task is, called reentrant function.
• A function is reentrant if:
• It should not use non-atomic variables unless they are
stored in stack of calling task or are private variables of
that task
• Should not call anther non-reentrant function.
• Should not use hardware in non-atomic way.

63
7.SEMAPHORES
• A semaphore is akin to disabled interrupt for an ISR.
• A semaphore is taken and released.
• As long as a semaphore is taken by a task it won’t be
interrupted.
• Terms like get & give, take & release, pend & post, wait
& signal etc. are used.
• If a task calls take semaphore and does not call release
semaphore then any other task calling take semaphore
will be blocked.

64
7.SEMAPHORES
Struct void levels task( void)
/* low priority*/
{ {
long tanklevel; while(true)
long timeupdated; {
takesemaphore();
}tankdata[max_tanks]; set tankdata[I].timeupdate
Void Buttontask( void) /*higher set tankdata[I].tanklevel
priority*/ releasesemaphore();
}
{ }
while(true) void main( void )
{ {
unblock on button push and respond initrtos():
I=get id of tank where button pushed starttask(buttontask, high);
takesemaphore(); starttask(levelstask, low);
printf(“ time=%ld and level=%ld”, startrtos();
tankdata[I].timeupdatetankdata[I].
tanklevel); }
releasesemaphore();
}
}

65
7.SEMAPHORES

• Assume levels task took semaphore.


• If button is pushed, because of lower priority levels task
moves to ready state.
• Button task tries to take a semaphore and since it is not
released yet levels task is pushed into blocked state.
• RTOS looks for ready tasks and since levels is ready it is
run until it releases semaphore.
• Semaphores make functions reentrant.

66
7.1 MULTIPLE SEMAPHORES

• Many RTOSs support multiple semaphores.


• Some data can be protected using semaphorea, some by
semaphoreb etc.
• The system response improves by this method
• RTOS does not know which semaphore protects which
data, its designer’s responsibility.
• Semaphores can be used as signaling devices between
tasks and ISRs aswell.
• A semaphore can be released from inside an ISR
unblocking a task.
• A semaphore can be acquired from an ISR blocking task

67
7.2 SEMAPHORE PROBLEMS
Priority inversion:
• Task a, task b and task c are in decreasing order of
priority.
• Task c acquires semaphore.
• Task b gets unblocked and takes control.
• Task a wants semaphore and gets blocked.
• Task c can’t release semaphore because task b is running.
• So task b holds up higher priority task a, hence priority
inversion.
• Solved by priority inheritance where task c is temporarily
elevated above task b.

68
7.2 SEMAPHORE PROBLEMS

Deadlock or deadly embrace

Void task1( void )


{
take(semaphore1); Void task1( void )
take(semaphore2); {
a=b; take(semaphore2);
give(semaphore1); take(semaphore1);
give(semaphore2);
b=a;
}
give(semaphore1);
give(semaphore2);
}

69
7.2 SEMAPHORE PROBLEMS

 Forget to initialize semaphore.


 Forget to take semaphore.
 Forget to give semaphore.
 Taking wrong semaphore.
 Holding semaphore too long.

70
7.3 SEMAPHORES TYPES

• Counting semaphores: Taking increments count


and giving up decrements count. Blocks when
count is zero.
• Resource semaphores: These are released only
by a task and cannot be used to communicate
with ISRs.
• Mutex semaphores: These automatically take
care of priority inversion.

71
8.MESSAGE QUEUES

• The inter task communication is achieved using above


said tools.
• Where to use?
• Let’s assume two tasks 1 & 2 are of high priority and have
important things to do.
• If from time to time these tasks detect error conditions that
need to be reported, but reporting is a time consuming
process.
• In these situations it’s preferable to call a separate task
errors task which takes care of errors.
• Errors are queued and sent to errors task, which takes care
of things to do.

72
8.1 PITFALLS

• Reading wrong information from wrong task.


• Improper interpretation, writing of char pointer
and reading as int pointer.
• Running out of space.

73
9.COMPARISON OF
COMMUNICATION METHODS

 Semaphores are fastest and simplest but can transfer only


one bit of information, taking or releasing of semaphore.
 Event though convey similar amount of information
compared to a semaphore, a task can wait for more than
one event at the same time.
 Queues can send larger data but take more processor time
and can cause more bugs. These points apply to mail
boxes as well as pipes.

74
10.ISR IN RTOS ENVIRONMENT

• Two rules are to be followed when using ISR’s


with RTOS.
• Rule 1: ISR must not call any RTOS function that
might block caller.
• Rule 2: An interrupt routine may not call any
RTOS function that may cause switching of tasks
unless RTOS knows it’s an ISR rather than a task
which is calling the function.

75
10. IMPILICATIONS: RULE 1

static int tem[2]; void testtemp( void )


void interrupt readtemp( void ) {
{ int temp0,temp1;
while( 1 ) while( 1 )
{ {
getsem();
getsem();
temp[0] = read
temp0 = temp[0];
temp[1] = read
givesem();
temp1 = temp[1];
} if(temp0 != temp1) set alarm;
} givesem();
}
}

76
10. IMPILICATIONS: RULE 2

EXPECTED BEHAVIOUR OF RTOS WITH ISR


77
10. IMPILICATIONS: RULE 2

BEHAVIOUR WHEN THERE IS NO DIFFERENCE BETWEEN


ISR AND A TASK
78
10. IMPILICATIONS: RULE 2

RTOS INTERCEPTS INTERRUPTS AND CALLS ISR

79
10. IMPILICATIONS: RULE 2

ISR INVOKES RTOS USING ISR SEMAPHORES


80
10.1 NESTED INTERRUPTS WITH
RTOS

81