You are on page 1of 21

Unidad Didctica 5: Sistemas Operativos de Tiempo Real

Sistemas embebidos para tiempo real

ndice
Introduccin Tareas y el planificador (scheduler) Tareas y datos Semforos y datos compartidos

Introduccion a los RTOS

Sistemas embebidos de tiempo real

29

Datos compartidos
Comunicacin entre tareas:
enfoque ms sencillo: estructura/variable compartida

Exclusin mutua
asegurar acceso exclusivo para evitar datos corruptos

Mtodos:
Deshabilitar interrupciones Operacin Test&Set atmica (eg. 68000) Deshabilitar scheduling Semforos...
Sistemas embebidos de tiempo real 30

Introduccion a los RTOS

Semforos y recursos compartidos


Recurso: tramo de va

Introduccion a los RTOS

Sistemas embebidos de tiempo real

31

Semforos en RTOS
Nomenclatura:
TakeRelease (posta, llave) RaiseLower (semforo ferroviario) WaitSignal PendPost (esperar-avisar)

Semforos para exclusin mutua (MutEx)


proteger recursos compartidos: datos compartidos

Semforos para comunicacin entre tareas.

Introduccion a los RTOS

Sistemas embebidos de tiempo real

32

Semforos: proteccin de datos


/* Levels Task */

struct { long lTankLevel; long lTimeUpdated; } tankdata[MAX_TANKS];

void vCalculateTankLevels(void) { /* low priority task */ int i = 0; while (TRUE) { !! read float levels in task i !! do bunches of calculations TakeSemaphore( ); tankdata[i].lTimeUpdated = !! current time tankdata[i].lTankLevel = !! result of long calculation ReleaseSemaphore( ); !! pick next tank to handle, etc. i = !! next tank } } Introduccion a los RTOS

/* Button Task */ void vRespondToButton(void) { /* high priority task */ int i; while (TRUE) { !! Block until button pressed i = !! ID of button pressed TakeSemaphore( ); !! output ITankLevel !! output ITimeUpdated ReleaseSemaphore( ); }

} Sistemas embebidos de tiempo real

33

Flujo de ejecucin con semforos


vCalculateTankLevel
TakeSemaphore( ); tankdata[i].lTimeUpdated

vRespondToButton
usuario presiona un botn se desbloquea tarea botn semforo no disponible se bloquea tarea botn liberando el semforo se desbloquea la tarea botn tarea botn se bloquea continua con tarea niveles

!! Block until button pressed i = !! ID of button pressed TakeSemaphore( );

tankdata[i].lTankLevel ReleaseSemaphore( );

!! output tank level, timestamp ReleaseSemaphore( );

Introduccion a los RTOS

Sistemas embebidos de tiempo real

34

Ejemplo de semforos: C/OS


Notacin
el prefijo OS indica funciones del kernel Creacin/inicializacin: OSSemCreate() Tomar y liberar un semforo: OSSemPend(),OSSemPost() Estructura OS_EVENT representa el semforo

Parmetros:
OS_EVENT *p_semTemp; p_semTemp = OSSemCreate(1); OSSemPend(p_semTemp,WAIT_FOREVER);

Otro servicio del RTOS


Retardo: OSTimeDly()
Introduccion a los RTOS Sistemas embebidos de tiempo real 35

#define PRIORITY_READ 11

#define PRIORITY_CONTROL 12 #define STK_SIZE 1024 static unsigned ReadStk[STK_SIZE]; static unsigned CtrlStk[STK_SIZE]; static int iTemperatures[2]; OS_EVENT *p_semTemp; void main (void) { OSInit( ); OSTaskCreate (vReadTmpTsk, NULLP, (void *) &ReadStk[STK_SIZE], PRIORITY_READ); OSTaskCreate (vCtrlTask, p_semTemp = OSSemCreate(1); OSStart ( ); } void vRdTmpTsk (void) { while (TRUE) { OSTimeDly(5); OSSemPend(p_semTemp,WAIT_FOREVER); !! read in iTemperatures[0]; !! read in iTemperatures[1]; OSSemPost (p_semTemp); } } void vCtrlTsk(void) { while (TRUE) { OSSemPend (p_semTemp, WAIT_FOREVER); if(iTemperatures[0] != iTemperatures[1]) !! set off howling alarm; OSSemPost (p_semTemp); !! do other useful work } } NULLP, (void *) &CtrlStk[STK_SIZE], PRIORITY_CONTROL);

Semforos y funciones reentrantes


void Task1(void) { vCountErrors (1); } void Task2(void) { vCountErrors (2); } static int cErrors; void vCountErrors(int cNewErrors) { cErrors += cNewErrors; }

Introduccion a los RTOS

Sistemas embebidos de tiempo real

37

Semforos y funciones reentrantes


void Task1(void) { vCountErrors (1); } void Task2(void) { vCountErrors (2); } static int cErrors; static NU_SEMAPHORE semErrors; void vCountErrors(int cNewErrors) { NU_Obtain_Semaphore(&semError,NU_SUSPEND); cErrors += cNewErrors; NU_Release_Semaphore(&semError); }

Terminologa:
Se ha "protegido cErrors con semforos

Notacin:
En este caso RTOS: Nucleus (prefijo NU)
Introduccion a los RTOS Sistemas embebidos de tiempo real 38

Mltiples semforos
En un sistema pueden coexistir varios semforos:
Cada semforo protege un slo recurso compartido. Cada tarea slo tiene que esperar si el recurso que tiene que utilizar est bloqueado. El RTOS no sabe qu recursos estn protegidos por qu semforos. Eso es tarea del programador.

Counting semaforos
Control sobre un conjunto de N recursos.

Introduccion a los RTOS

Sistemas embebidos de tiempo real

39

Semforos para sealizacin


Semforo como mtodo de comunic. entre tareas. Ejemplo impresin de reportes:
Datos:
Buffer de donde se arma el reporte, nmeros lneas totales e impresas.

Tareas:
PrinterTask: espera por el reporte y luego enva lnea a lnea desde el buffer a la impresora.

ISR:
La impresora interrumpe al final de cada lnea y carga la siguiente lnea a imprimir.
Introduccion a los RTOS Sistemas embebidos de tiempo real 40

Semforos para sealizacin


static static static static char a_chPrint[10][21]; /*outp buf */ int iLinesTotal; int iLinesPrinted; OS_EVENT *semPrinter; void vPrinterTask(void) { BYTE byError; int wMsg; while (TRUE) { /* wait for a job to print */ wMsg = (int) OSQPend (QPrinterTask, WAIT_FOREVER, &byError); !! Format the report into a_chPrint iLinesTotal = !! count of lines in report /* print first line of report */ iLinesPrinted = 0; vHardwarePrinterOutputLine( a_chPrint[iLinesPrinted++]); OSSemPend(semPrinter, WAIT_FOREVER, &byError); } }

void vPrinterInterrupt (void) { if (iLinesPrinted == iLinesTotal) /* report done: release semaphore */ OSSemPost(semPrinter); else /* report not done: print next line */ vHardwarePrinterOutputLine( a_chPrint[iLinesPrinted++]); }

Introduccion a los RTOS

Sistemas embebidos de tiempo real

41

Discusin
Semforo usado como seal:
Tarea que enva: hace un post. Tarea que recibe: hace un pend. Comparacin con exclusin mutua:
la misma tarea llama a pend, y luego post.

Especial cuidado con:


Valor inicial del semforo: debe ser elegido bien.
En el ejemplo el semforo fue inicializado como no disponible. Depende de la aplicacin.

Orden cuando existen mltiples pends.


En el ejemplo, la tarea espera por una cola y el semforo
Introduccion a los RTOS Sistemas embebidos de tiempo real 42

Problemas
Olvidar de tomar (pend) el semforo. Olvidar de liberar (post) el semforo. Tomar o liberar el semforo equivocado. Ocupar el semforo por demasiado tiempo. Inversin de prioridad Deadlock, o abrazo mortal

Introduccion a los RTOS

Sistemas embebidos de tiempo real

43

Inversin de prioridad
Tarea A se desbloquea. Tarea B se desbloquea. RTOS conmuta a A. RTOS conmuta a B. Tarea A trata de tomar el semaforo que tiene C Tarea C toma el y se bloquea. semaforo que Tarea B se ejecuta por mucho comparte con A tiempo Tarea A Tarea C no puede ejecutar para liberar el semaforo. Task A se pierde un deadline.

Prioridad creciente

Tarea B Tarea C

tiempo

Introduccion a los RTOS

Sistemas embebidos de tiempo real

44

Abrazo mortal
OS_EVENT *p_sem_A, *p_sem_B; int a, b; /* Variables compartidas */ void Tarea1(void) { OSSemPend(p_sem_A, WAIT_FOREVER); OSSemPend(p_sem_B, WAIT_FOREVER); a = b; OSSemPost(p_sem_B); OSSemPost(p_sem_A); } void Tarea2(void) { OSSemPend(p_sem_B, WAIT_FOREVER); OSSemPend(p_sem_A, WAIT_FOREVER); b = a; OSSemPost(p_sem_A); OSSemPost(p_sem_B); } Introduccion a los RTOS Sistemas embebidos de tiempo real 45

Opciones para datos compartidos


Deshabilitar interrupciones
manera ms drstica afecta tiempo de respuestas de todas las tareas y ISR nico mtodo para compartir datos con ISR

Semforos
afecta aquellas que esperan el mismo semforo, sin impacto en ISR aumenta probabilidad de errores de programacin

Deshabilitar conmutacin de tareas (deshab. planificador)


planificador (scheduler) no conmuta tareas funcionalidad presente en algunos RTOS Overhead para habilitar y deshabilitar es pequeo. Tiempo de respuesta: afecta todas las tareas Introduccion a los RTOS Sistemas embebidos de tiempo real pero no ISR

46

Resumen
RTOS
Caractersticas, diferencias con OS convencional

Tareas
Bloque fundamental, estados, contexto, scheduler...

Funciones reeentrantes Recursos compartidos:


Datos, hardware.

Semforos
Mutex o comunicacin entre tareas, problemas

Opciones para resolver bug de datos compartidos.


Introduccion a los RTOS Sistemas embebidos de tiempo real 47

Bibliografa
An Embedded Software PrimerDavid E. Simon
Chapter 6: Introduction to Real-Time Operating Systems

MicroC OS II: The Real Time Kernel

Introduccion a los RTOS

Sistemas embebidos de tiempo real

48

You might also like