0% found this document useful (0 votes)
16 views114 pages

Embedded RTOS - 2

Uploaded by

rhood2656
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views114 pages

Embedded RTOS - 2

Uploaded by

rhood2656
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 114

Embedded Systems

Chapter – 6

Real-Time Operating System

8/11/2015 1
6. Real-Time Operating System [8 Hrs.]

6.1 Operating System Basics


6.2 Task, Process, and Threads
6.3 Multiprocessing and Multitasking
6.4 Task Scheduling
6.5 Task Synchronization
6.6 Device Drivers
8/11/2015 2
How the increasing need for time critical
response for task/events is addressed in
embedded applications?
-Assign priority to task & execute the high priority
task when the task is ready to execute.
-Dynamically change the priorities of tasks if
required on a need basis.
- Schedule the execution of tasks based on the
priorities.
-Switch the execution of task when a task is waiting
for an external event or a system resource
including I/O device operation.
8/11/2015 3
Operating System Basics
- acts as a bridge between the user application/
tasks & the underlying system resources through
a set of system functionalities and services.
- Manages the system resources and makes them
available to the user application/task on a need
basis.
- Primary functions are:
- Make the system convenient to use
- Organize & manage the system resources
efficiently and correctly.
8/11/2015 4
Fire alarm system: an example

Central server

TCP/IP over radio

Controllers: ARM based

Low bandwidth radio links

Sensors: microcontroller based

8/11/2015 5
Fire Alarm System
• Problem
– Hundreds of sensors, each fitted with Low Range Wireless
• Sensor information to be logged in a server & appropriate action
initiated
• Possible Solution
– Collaborative Action
• Routing
– Dynamic – Sensors/controllers may go down
– Auto Configurable – No/easy human intervention.
– Less Collision/Link Clogging
– Less no of intermediate nodes
» Fast Response Time
– Secure

8/11/2015 6
RTOS: Target Architectures

Processors MIPS

Microcontrollers ~20
ARM7 100-133
ARM9 180-250
Strong ARM 206
Intel Xscale 400
Mips4Kcore 400
X86
8/11/2015 7
Operating System Basics contd…
contd …

The Kernel is:


- core of operating system
- responsible for managing the system resources
and the communication among the hardware
and other system services.
- act as the abstraction layer between system
resources and user applications.
- contains a set of system libraries and services.
8/11/2015 8
Operating System Basics contd…
contd …

8/11/2015 9
Operating System Basics contd…
contd …

Process Management:
• deals with managing the processes/tasks.
• Includes setting up the memory space for the process
• Loading the process’s code into the memory space
• Allocating system resources
• Scheduling and managing the execution of the process
• Setting up and managing the process control Block
(PCB)
• Inter process communication and synchronization
• Process termination/deletion
8/11/2015 10
Operating System Basics contd…
contd …

Primary Memory Management:


• Refers to the volatile memory (RAM) where processes
are loaded and variables and shared data associated
with each process are stored.
• Memory Management Unit (MMU) of the kernel is
responsible for
• Keeping track of which part of the memory area is
currently used by which process
• Allocating and De-allocating memory space on a
need basis (DMA)
8/11/2015 11
Operating System Basics contd…
contd …

File System Management: responsible for


• The creation, deletion and alteration of files.
• Creation, deletion and alteration of directories
• Saving of files in the secondary storage
memory
• Providing automatic allocation of file space
based on the amount of free space available
• Providing a flexible naming convention for the
files.
8/11/2015 12
Operating System Basic contd…
contd …

I/O System (Device)Management


• loading and unloading of device drivers
• exchanging information and the system
specific control signals to and from the device
Secondary storage management
•Disk storage allocation
•Disk scheduling (time interval at which the
disk is activated to backup data)
•Free disk space management
8/11/2015 13
Operating System Basic contd…
contd …

Protection systems (deals


( with
implementing the security policies to
restrict the access to both user and system
resources by different application or
processes or users)
users

Interrupt Handler (Kernel


( provides handler
mechanism for all external/internal
interrupts generated by the system)
8/11/2015
system 14
Operating System Types contd…
contd …

General Purpose Operating System (GPOS)


Real - Time Operating System (RTOS)
• Implies deterministic timing behavior
• Means the OS services consumes only known and
expected amounts of time regardless the number of
services.
• Implements policies and rules concerning time critical
allocation of a system’s resources
• Applications should run in which order and how much
time need to be allocated for each application.
8/11/2015 15
– A more complex software architecture is needed to handle multiple tasks,
coordination, communication, and interrupt handling – an RTOS
architecture

– Distinction:
• Desktop OS – OS is in control at all times and runs applications, OS runs
in different address space
• RTOS – OS and embedded software are integrated, ES starts and
activates the OS – both run in the same address space (RTOS is less
protected)
• RTOS includes only service routines needed by the ES application
• RTOS vendors: VsWorks, VTRX, Nucleus, LynxOS, uC/OS
• Most conform to POSIX (IEEE standard for OS interfaces)
• Desirable RTOS properties: use less memory, application programming
interface, debugging tools, support for variety of microprocessors,
already-debugged network drivers

8/11/2015 16
Hard and Soft Real Time Systems
• Hard Real Time System
– Failure to meet deadlines is fatal
– example : Flight Control System

• Soft Real Time System


– Late completion of jobs is undesirable but not fatal.
– System performance degrades as more & more jobs miss
deadlines
– Online Databases

• Qualitative Definition.

8/11/2015 17
Hard and Soft Real Time Systems
(Operational Definition)
• Hard Real Time System
– Validation by provably correct procedures or extensive
simulation that the system always meets the timings
constraints

• Soft Real Time System


– Demonstration of jobs meeting some statistical
constraints suffices.

• Example – Multimedia System


– 25 frames per second on an average

8/11/2015 18
Operating System Types contd…
contd …

The Real-Time Kernel: is highly specialized


and it contains only the minimal set of
services required for a running the user
application/tasks. Basic functions are
• Task/Process management
• Task/Process scheduling
• Task/Process synchronization
• Error/Exception handling
• Memory management
• Interrupt handling time management
8/11/2015 19
Tasks & Task State
Task are very simple to write: under most RTOSs a task
is simply a subroutine.
1. Running— the microprocessor is executing the instructions that
make up this task. one microprocessor, and hence only one task
that is in the running state at any given time.
2. Ready— some other task is in the running state but that this
task has things that it could do if the microprocessor becomes
available. Any number of tasks can be in this state.
3. Blocked— this task hasn't got anything to do right now, even
if the microprocessor becomes available. Tasks get into this state
because they are waiting for some external event. For example, a
task that handles data coming in from a network will have nothing
to do when there is no data. A task that responds to the user
when he presses a button has nothing to do until the user presses
the button. Any number of tasks can be in this state as well.
8/11/2015 20
• ES application makes calls to the RTOS functions to start tasks,
passing to the OS, start address, stack pointers, of the tasks
• Task States:
– Running
– Ready (possibly: suspended, pended)
– Blocked (possibly: waiting, dormant, delayed)
– [Exit]

– Scheduler – schedules/shuffles tasks between Running and Ready


states
– Blocking is self-blocking
blocking by tasks, and moved to Running state via other
tasks’ interrupt signaling (when block-factor is removed/satisfied)
– When a task is unblocked with a higher priority over the ‘running’ task,
the scheduler ‘switches’ context immediately (for all pre-emptive
RTOSs)

8/11/2015 21
Tasks

Blocked Ready

Task States
Running
8/11/2015 22
Tasks
Here are answers to some common questions
about the scheduler and task states'.

How does the scheduler know when a task has


become blocked or unblocked?

What happens if all the tasks are blocked?

What if two tasks with the same priority are


ready?
8/11/2015 23
• Tasks – 1

– Issue – Scheduler/Task signal exchange for block-unblock of


tasks via function calls
– Issue – All tasks are blocked and scheduler idles forever (not
desirable!)
– Issue – Two or more tasks with same priority levels in Ready
state (time-slice, FIFO)

– Example: scheduler switches from processor-hog vLevelsTask


to vButtonTask (on user interruption by pressing a push-
button), controlled by the main() which initializes the RTOS,
sets priority levels, and starts the RTOS
Tasks

8/11/2015 25
Tasks
Microprocessor Responds to a Button under an RTOS;

8/11/2015 26
Tasks
RTOS Initialization Code

8/11/2015 27
• Tasks and Data

– Each tasks has its won context - not shared, private


registers, stack, etc.
– In addition, several tasks share common data (via
global data declaration; use of ‘extern’ in one task to
point to another task that declares the shared data
– Shared data caused the ‘shared-data problem’
without solutions or use of ‘Reentrancy’
characterization of functions

– (See Fig 6.5, Fig 6.6, Fig 6.7, and Fig 6.8)
Tank Monitoring System

8/11/2015 30
Tasks in the Underground Tank System

8/11/2015 31
8/11/2015
Tank Monitoring Design

32
• Tasks – 2

• Reentrancy – A function that works correctly regardless


of the number of tasks that call it between interrupts

• Characteristics of reentrant functions –


– Only access shared variable in an atomic-way, or when
variable is on callee’s stack
– A reentrant function calls only reentrant functions
– A reentrant function uses system hardware (shared resource)
atomically
• Inspecting code to determine Reentrancy:

– See Fig 6.9 – Where are data stored in C? Shared, non-shared,


shared,
or stacked?

– See Fig 6.10 – Is it reentrant? What about variable fError? Is


printf reentrant?

– If shared variables are not protected, could they be accessed


using single assembly instructions (guaranteeing non-
atomicity)?
• Semaphores and Shared Data – A new tool for atomicity

– Semaphore – a system resource for implementing mutual


exclusion in shared resource access or restricting the access to
the shared resources (to avoid shared-data problems in RTOS)
– Protection at the start is via primitive function, called take,
indexed by the semaphore
– Protection at the end is via a primitive function, called release,,
also indexed similarly

– Simple semaphores – Binary semaphores are often adequate


for shared data problems in RTOS
• Semaphores and Shared Data – 1

– RTOS Semaphores & Initializing Semaphores

– Using binary semaphores to solve the ‘tank monitoring’ problem


– (See Fig 6.12 and Fig 6.13)

– The nuclear reactor system: The issue of initializing the semaphore


variable in a dedicated task (not in a ‘competing’ task) before initializing
the OS – timing of tasks and priority overrides, which can undermine the
effect of the semaphores

– Solution: Call OSSemInit() before OSInit()

– (See Fig 6.14)


• Semaphores and Shared Data – 2

– Reentrancy, Semaphores, Multiple Semaphores, Device Signaling,

– Fig 6.15 – a reentrant function, protecting a shared data, cErrors, in


critical section

– Each shared data (resource/device) requires a separate semaphore for


individual protection, allowing multiple tasks and data/resources/devices
to be shared exclusively, while allowing efficient implementation and
response time

– Fig 6.16 – example of a printer device signaled by a report-buffering


buffering task,
via semaphore signaling, on each print of lines constituting the formatted
and buffered report
• Semaphores and Shared Data – 3

– Semaphore Problems – ‘Messing up’ with semaphores


• The initial values of semaphores – when not set properly or at the
wrong place
• The ‘symmetry’ of takes and releases – must match or correspond –
each ‘take’ must have a corresponding ‘release’ somewhere in the ES
application
• ‘Taking’ the wrong semaphore unintentionally (issue with multiple
semaphores)
• Holding a semaphore for too long can cause ‘waiting’ tasks’ deadline to
be missed
• Priorities could be ‘inverted’ and usually solved by ‘priority
inheritance/promotion’
• (See Fig 6.17)
• Causing the deadly embrace problem (cycles)
• (See Fig 6.18)
• Semaphores and Shared Data – 4

– Variants:
• Binary semaphores – single resource, one-at-a time, alternating in use
(also for resources)
• Counting semaphores – multiple instances of resources,
increase/decrease of integer semaphore variable
• Mutex – protects data shared while dealing with priority inversion
problem

– Summary – Protecting shared data in RTOS


• Disabling/Enabling interrupts (for task code and interrupt routines),
faster
• Taking/Releasing semaphores (can’t use them in interrupt routines),
slower, affecting response times of those tasks that need the
semaphore
• Disabling task switches (no effect on interrupt routines), holds all other
tasks’ response
Process:
- is a program, or part of it execution.
- an instance of a program in execution; multiple
instances of the same program can execute
simultaneously.
- Requires various system resources like CPU for
executing the process, memory for storing the
code corresponding to the process and
associated variables, I/O devices for information
exchange.
- is sequential in execution.
8/11/2015 58
Process Structure:

Process
Stack
Stack Pointer

Working registers

Status registers

Program Counter (PC) Code memory


corresponding to the
Process
8/11/2015 59
Process Life Cycle – process
changes its state from newly
created to execution
completed

Created state – a process is


being created is referred. OS
recognizes a process but no
resources are allocated to
the process.

Ready State – the state,


where a process is incepted
into the memory and
awaiting the processor time
for execution.
Process states and state transition representation
8/11/2015 60
Ready List – queue
maintained by the OS.

Running State – the state


where in the source code
instructions corresponding
to the process is being
executed.

Blocked State/Wait state –


refers to a state where a
running process is
temporarily suspended from
execution and does not have
immediate access to
resources..
Process states and state transition representation
8/11/2015 61
Completed State – a state
where the process completes its
execution

State transition – the transition


of a process from one state to
another

Process Management – deals


with the creation of a process,
setting up the memory space for
the process, loading the
process’s code into the memory
space, allocating system
resources, setting up a Process
Control Block (PCB) for the
process and process termination Process states and state transition representation
/ deletion.
8/11/2015 62
Process Management
• Deals with the creation of a process
• Setting up the memory space for the
process
• Loading the process’s code into the
memory space
• Allocating system resources
• Setting up a Process Control Block (PCB)
for the process termination / deletion
8/11/2015 63
Threads:
Stack memory for thread 1

Stack Memory for


• Is the primitive that
Stack memory for thread 2
can execute code

process
• Is a single sequential
flow of control Data memory for process
within a process Code memory for process
• Also known as light Memory organization of a process
weight process and its associated Threads

• A process can have many threads of execution


8/11/2015 64
Threads: contd. …

•Different threads, which are part of a


process, share the same address space;
meaning they share the data memory,
code memory and the heap memory area.

•Threads maintain their own thread status


(CPU register values), Program Counter
(PC) and stack.
8/11/2015 65
Multithreading
• Application may
complex and lengthy
• Various sub -
operations like
getting input from
I/O devices
connected to the
processor
• Performing some
internal calculations /
operations
• Updating some I/O
devices
8/11/2015 66
Multithreading ……
all the sub-functions of a task are executed in sequence (?)
– the CPU utilization may not be efficient
Advantages of multiple threads to execute:
• Better memory utilization (same process share the
address space of the same memory & reduces complexity
of inter threads comm.)
• Speed up execution of the process (splitting into different
threads, when one thread enters a wait state, the CPU
can be utilized by the other threads of the process that do
not require the event, which other thread is waiting, for
processing)
• Efficient CPU utilization. CPU – engaged all time.
8/11/2015 67
Multithreading ……
Thread Standards: deals with different standards available
for thread creation and management; utilized by OS
Thread Class libraries are:
• POSIX Threads (Portable Operating System Interface)
• Win 32 Threads
• Java Threads

8/11/2015 68
Multithreading ……
• POSIX Threads (Portable Operating System Interface)

POSIX.4 standard deals with the Real-Time


Real extensions
POSIX.4a standard deals with thread extensions

““Pthreads”” library defines the set of POSIX thread creation


and management functions in C language

8/11/2015 69
8/11/2015 70
8/11/2015 71
Win 32 Threads:
• are the threads supported by various flavors of windows
OS.
• Win 32 Application Programming Interface (Win 32 API)
libraries provide the standard set of Win 32 thread
creation and management functions.
• Win 32 threads are created with the API

HANDLE CreateYThread (LPSECURITY_ATTRIBUTES


lpThreadAttributes, DWORD dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddresss, LPVOID
lpParameter, DWORD dwCreationFlags, LPWORD
lpThreadId ) ;
8/11/2015 72
Thread Process
• is a single unit of execution and • Is a program in execution &
is part of process contains 1 or more threads
• Does not have its own data • Has its own code memory, data
memory and heap memory. memory & stack memory
Shares these memory with other • Contains at least one thread
threads of the same process • Threads within a process share
the code, data & heap memory.
• Cannot live independently; it Each thread holds separate
lives within the process memory area for stack (shares
• Can be multiple threads in a the total stack memory of the
process; the first thread (main process)
thread) calls the main function • Are very expensive to create.
and occupies the start of stack Involves many OS overhead
memory of the process • Context switching is complex and
• Are very inexpensive to create involves lot of OS overhead & is
comparatively slower
• Context switching is inexpensive • If process dies, the resources
and fast allocated to it are reclaimed by
• If a thread expires, its stack is OS & all the associated threads
reclaimed by the process of the process also dies
8/11/2015 73
Multiprocessing & Multitasking

Context
8/11/2015 switching 74
Real-Time Kernels
• A process is an abstraction of a running
program and is the logical unit of work
scheduled by OS

• Threads are light-weighted processes sharing


resources of the parent process

• RTOS task management functions: scheduling,


dispatching, intercommunication and
synchronization
8/11/2015 75
• The kernel of the OS is the smallest portion
that provides for task management functions

• A scheduler determines which task will run


next

• A dispatcher provides a necessary bookkeeping


to start the next task

• Intertask communication and synchronization


assures that the tasks cooperate
8/11/2015 76
8/11/2015 77
Pseudo-kernels
•Polled Loop
For(;;){/*do forever*/
if (packet_here){/*check flag*/
process_data();/*process data*/ packet_here=0;/*reset flag*/
}
}
•Synchronized polled loop
For(;;){/*loop forever*/
if (flag){ pause(20); /* wait 20 ms to avoid switch-bounce*/
process_event(); flag=0;
}
}

8/11/2015 78
Cyclic Executives
For(;;){/* do forever in round-robin fashion*/
Process1();
Process2();
..
ProcessN();
}
Different rates example:
For(;;){/* do forever in round-robin fashion*/
Process1();
Process2();
Process3();/*process 3 executes 50% of the time*/
Process3();
}

8/11/2015 79
State-Driven Code
It uses if-then, case statements or finite state automata to break up
processing of functions into code segments
For(;;){/*dining philosophers*/
switch (state)
case Think: pause(random()); state=Wait; break;
case Wait: if (forks_available()) state=Eat;
case Eat: pause(random()); return_forks(); state=Think;
}
Return forks
}
Eat
Think Take forks

Take forks
Wait forks
Wait
8/11/2015 80
Coroutines
Void process_i(){//code of the i-th process
switch (state_i){// it is a state variable of the i-th process
case 1: phase1_i(); break;
case 2: phase2_i(); break;
..
case N: phaseN_i();break; 1 2 N
}
}
Dispatcher(){
For(;;){ /*do forever*/
Dispatcher
process_1();
..
process_M();
}
8/11/2015 81
Interrupt-Driven Systems
Interrupt Service Routine (ISR) takes action in response to the interrupt
Reentrant code can be used by multiple processes. Reentrant ISR can
serve multiple interrupts. Access to critical resources in mutually
exclusive mode is obtained by disabling interrupts
On context switching save/restore:
•General registers
•PC, PSW
•Coprocessor registers
•Memory page register
•Images of memory-mapped I/O locations
The stack model is used mostly in embedded systems
8/11/2015 82
Pseudocode for Interrupt Driven System
Main(){//initialize system, load interrupt handlers
init();
while(TRUE);// infinite loop
}
Intr_handler_i(){// i-th interrupt handler
save_context();// save registers to the stack
task_i(); // launch i-th task
restore_context();// restore context from the stack
}
Work with a stack:
Push x: SP-=2; *SP=x;
Pop x: x=*SP; SP+=2;

8/11/2015 83
Preemptive Priority System
A higher-priority task is said to preempt a lower-priority task if it interrupts the lower-
priority task
The priorities assigned to each interrupt are based on the urgency of the task associated
with the interrupt
Prioritized interrupts can be either priority or dynamic priority
Low-priority tasks can face starvation due to a lack of resources occupied by high-priority
tasks
In rate-monotonic systems higher priority have tasks with higher frequency (rate)

Hybrid systems
Foreground-background systems (FBS)– polling loop is used for some job (background task –
self-testing, watchdog timers, etc)
Foreground tasks run in round-robin, preemptive priority or hybrid mode
FBS can be extended to a full-featured real-time OS
8/11/2015 84
The Task Control Model of Real-Time Operating System
Each task is associated with a structure called Task Control Block
(TCB). TCB keeps process’ context: PSW, PC, registers, id, status, etc
TCBs may be stored as a linked list
A task typically can be in one of the four following states:
1) Executing; 2) Ready; 3) Suspended (blocked); 4) Dormant (sleeping)

Ready Dormant

Executing
Suspended

RTOS maintains a list of the ready tasks’ TCBs and another list for the suspended tasks
When a resource becomes available to a suspended task, it is activated
8/11/2015 85
Process Scheduling
Pre
Pre-run time and run-time
time scheduling. The aim is to meet time restrictions
Each task is characterized typically by the following temporal parameters:
1) Precedence constraints; 2) Release or Arrival time ri , j of j-th instance
of task i; 3) Phase  i ; 4) Response time; 5) Absolute deadline d i
6) Relative deadline Di
7) Laxity type – notion of urgency or margin in a task’s execution
8) Period
pi
9) Execution time ei
i  ri ,1 ri , k  i  ( k  1) pi
d i , k   i  ( k  1) pi  Di
Assume for simplicity: all tasks are periodic and independent, relative deadline
is a period/frame, tasks are pre-emptible, preemption time is neglected

8/11/2015 86
Round-Robin Scheduling

8/11/2015 87
Cyclic Executives
Scheduling decisions are made periodically, rather than at arbitrary times
Time intervals during scheduling decision points are referred to as frames or
minor cycles, and every frame has a length, f, called the frame size
The major cycle is the minimum time required to execute tasks allocated to
the processor, ensuring that the deadlines and periods of all processes are
met
The major cycle or the hyperperiod is equal to the least common multiple
(lcm) of the periods, that is, lcm(p1,..,pn)
Scheduling decisions are made at the beginning of every frame. The phase of
each task is a non-negative integer multiple of the frame size.
Frames must be long enough to accommodate each task:

C1 : f  max ei
1i  n

8/11/2015 88
Cyclic Executives

Hyper period should be a multiple of the frame size:

C2 :  pi / f   pi / f  0

To insure that every task completes by its deadline, frames must be small
so that between the release time and deadline of every task, there is at
least one frame.

8/11/2015 89
Cyclic Executives
The following relation is derived for a worst-case scenario, which
occurs when the period of a process starts just after the
beginning of a frame, and, consequently, the process cannot be
released until the next frame:

C3 : 2 f  gcd( pi , f )  Di
t  t :
t  2 f  t   Di
2 f  (t   t )  Di
t   t  lp i  kf  lp i  kf  gcd( pi , f )
f  2 f  gcd( pi , f )  Di

8/11/2015 90
Cyclic Executives

8/11/2015 91
Cyclic Executives
For example, for tasks T1(4,1), T2(5,1.8), T3(20,1), T4(20,2), hyper-period is 20 (without
and with frames – f=2)

1 3 2 1 4 2 1

0 4 8 12

1 2 1 2

12 16 20

1 3 2 1 4 2 1

0 4 8 12

2 1 1 2

12 16 20

8/11/2015 92
Fixed Priority Scheduling – Rate-Monotonic Approach (RMA)

8/11/2015 93
Rate-Monotonic Scheduling
Theorem (RMA Bound). Any set of n periodic tasks is RM schedulable if the
processor utilization
n
ei
U    n(21/ n  1)
i 1 pi

8/11/2015 94
Dynamic-Priority Scheduling – Earliest-Deadline-First
Approach
Theorem (EDF Bound). A set of n periodic tasks, each of whose relative
deadline equals its period, can be feasibly scheduled by EDF if and only if
U 1

8/11/2015 95
Intertask Communication and Synchronization
•Buffering data
•Double-buffering

8/11/2015 96
Intertask Communication and Synchronization
Ring Buffers

8/11/2015 97
Intertask Communication and Synchronization

8/11/2015 98
Intertask Communication and Synchronization
Mailbox: void pend (int data, s); void post (int data, s);
Access to mailbox is mutually exclusive; tasks wait access granting

8/11/2015 99
Intertask Communication and Synchronization
•Queues – can be implemented with ring buffers
•Critical regions – sections of code to be used in the mutually exclusive
mode
•Semaphores – can be used to provide critical regions

8/11/2015 100
Intertask Communication and Synchronization
Mailboxes and Semaphores

8/11/2015 101
Intertask Communication and Synchronization
Semaphores and mailboxes
Sema mutex=0/*open*/, proc_sem=1;/*closed*/
Bool full_slots=0, empty_slots=1;
Void post( int mailbox, int message){
while (1){ wait(mutex);
if (empty_slots){
insert(mailbox, message); update(); signal(mutex);
signal(proc_sem); break;
}
else{ signal(mutex); wait(proc_sem);
}
}
}

8/11/2015 102
Intertask Communication and Synchronization
Semaphores and mailboxes
Void pend( int mailbox, int *message){
while (1){ wait(mutex);
if (full_slots){
extract(mailbox, message); update(); signal(mutex);
signal(proc_sem); break;
}
else{ signal(mutex); wait(proc_sem);
}
}
}

8/11/2015 103
Intertask Communication and Synchronization

Driver{ while(1){
if(data_for_I/O){
prepare(command);
V(busy); P(done);}
}}
Controller{while(1){
P(busy); exec(command);
V(done);
}}

8/11/2015 104
Intertask Communication and Synchronization
Counting Semaphores:
Wait: void MP(int &S){
S=S-1; while(S<0);
}
Signal: void MV(int &S){
S=S+1
}

8/11/2015 105
Intertask Communication and Synchronization

8/11/2015 106
Intertask Communication and Synchronization
Problems with semaphores:
Wait: void P(int &S){
while(S==TRUE);
S=TRUE;
}
LOAD R1,S ; address of S in R1
LOAD R2,1 ; 1 in R2
@1 TEST R1,I,R2 ; compare (R1)=*S with R2=1
JEQ @1 ; repeat if *S=1
STORE R2,S,I ; store 1 in *S
Interruption between JEQ and STORE, passing control to a next process,
can cause that several processes will see *S=FALSE

8/11/2015 107
Intertask Communication and Synchronization
The Test-and-Set Instruction
Void P(int &S){
while(test_and_set(S)==TRUE);//wait
}
Void V(int &S){
S=FALSE;
}
The instruction fetches a word from memory and tests the high-order
(or other) bit . If the bit is 0, it is set to 1 and stored again, and a
condition code of 0 is returned. If the bit is 1, a condition code of 1 is
returned and no store is performed. The fetch, test and store are
indivisible.

8/11/2015 108
Intertask Communication and Synchronization
Dijkstra’s implementation of semaphore operation (if test-and-set
instruction is not available):
Void P(int &S){
int temp=TRUE;
while(temp){
disable(); //disable interrupts
temp=S;
S=TRUE;
enable(); //enable interrupts
}
}

8/11/2015 109
Intertask Communication and Synchronization
Other Synchronization Mechanisms:
•Monitors (generalize critical sections – only one process can execute
monitor at a time. Provide public interface for serial use of resources
•Events – similar to semaphores, but usually all waiting processes are
released when the event is signaled. Tasks waiting for event are called
blocked

Deadlocks

8/11/2015 110
Intertask Communication and Synchronization
Deadllocks:

8/11/2015 111
Deadlocks
Four conditions are necessary for deadlock:

•Mutual exclusion

•Circular wait

•Hold and wait
• preemption
•No
Eliminating any one of the four necessary conditions will prevent deadlock
from occurring
One way to eliminate circular wait is to number resources and give all the
resources with the numbers greater or equal than minimal required to
processes. For example: Disk – 1, Printer – 2, Motor control – 3, Monitor – 4.
If a process wishes to use printer, it will be assigned printer, motor control
and monitor. If another process requires monitor, it will have wait until the
monitor will be released. This may lead to starvation.
starvation
8/11/2015 112
Deadlock avoidance
To avoid deadlocks, it is recommended :
• Minimize the number of critical regions as well as minimizing
their size
• All processes must release any lock before returning to the
calling function
• Do not suspend any task while it controls a critical region
• All critical regions must be error-free
• Do not lock devices in interrupt handlers
• Always perform validity checks on pointers used within critical
regions.
It is difficult to follow these recommendations
8/11/2015 113
A Separate Task Helps Control Shared Hardware

8/11/2015 114

You might also like