0% found this document useful (0 votes)
55 views22 pages

Rtos 1

This document discusses the fundamentals of real-time operating system based embedded firmware design, including learning about tasks, processes, scheduling, synchronization, inter-process communication, and device drivers in a real-time context. It covers topics like task priorities, preemptive multitasking, scheduling algorithms, shared memory, message passing, semaphores, and challenges of accessing shared resources concurrently. The goal is to understand how real-time operating systems address the increasing need for time-critical response in embedded applications.

Uploaded by

Vari
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)
55 views22 pages

Rtos 1

This document discusses the fundamentals of real-time operating system based embedded firmware design, including learning about tasks, processes, scheduling, synchronization, inter-process communication, and device drivers in a real-time context. It covers topics like task priorities, preemptive multitasking, scheduling algorithms, shared memory, message passing, semaphores, and challenges of accessing shared resources concurrently. The goal is to understand how real-time operating systems address the increasing need for time-critical response in embedded applications.

Uploaded by

Vari
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/ 22

10

10
Real-Time Operating
based Embedded System (RTOS)
System Design

LEARNING OBJECTIVES
e a m the banhs of m operutng system and the neenl for un
leam the mtermals of Rel Tme operating system
Operuting System aned the fundamentals RTOS
of based embedded firmware design
len the bav Aetnel servnes of an
operating system
eatn abut the lassifu afion
of operating systems
about the different real-time kermels and the
lean
features that make a kernel Real-Time
l e a n albout tasks, rO
esses and threads in the operating system context
leam about the structure of a process, the
v
dilferent states of a process, process life cycle and process management
Leam the concept of multithreading,
thread standards and thread scheduling
vUnderstand the difference between multiprocessing and multitasking,
Leam about the different types of multitasking (Co-operative,
Preemptive and Non-preemptive)
Leam about the FCFS/FIFO, LCFS7LIFO, SJF and priority based
Leam about the shortest remaining time (SRT), Round Robin and
task/process scheduling
priority based preemptive task/process scheduling
Learn about the different Inter Process Communication
(1PC) mechanisms used by tasks/process to communicate
and co-operate each other in a multitasking environment
Lean the different types of shared memory techniques (Pipes, memory mapped object, etc.) for IPC
Learn the different types of message passing techniques (Message queue, mailbox, signals, etc.) for IPC
learn the RPC based Inter Process Communication
lean the eed for task synchronisation in a multitasking environment
Lean the different issues related to the accessing
of a shared resource by multiple processes concurrently
Lean about 'Racing, Starvation', Livelock, "Deadlock', "Dining Philosopher's Problem,
ed Buffer Problem', 'Readers-Witers Problem' and Priority Inversion'
'Producer-Consumer/Bound-
Lean about the Prionity Inheritance' and Priority Ceiling' based Priority avoidance mechanisms
Lean the eed for task synchronisation and the different mechamisms for task synchronisation in a multitasking
environment
Lean about mutual exclusion and the dijferent poticies for mutual exclusion implementation
Learn about semaphores, different types ofsemaphores, mutex, critical section objects and events for task synchro-
nisation
Learn about device drivers, their role in an operating system based embedded system design, the structure of a
device driver, and interrupt handling inside device drivers
Understand the different functional and non-functional requirements that need to be addressed in the selection of
a Real-Time Operating System
I e previc oedd Systems
previous
execution. The chapter, we
within the loon super loop discussed about the Super loop based
As the loop. Here every executes the tasks task
execution model
number of task is sequentially
quentially in the order in which model for
firmwareor firmware
of the tasks task
involve increases, therepeated
ed
time int
at the tasks
regular intervals and the task execution
intervals
tasks are
are listed
pushed off in accordancewaiting for external events at which task gets serviced also
a
is
non-real time.
r
De
with vents or /O or increas
reases. If some
executed
ecution. This
is fixed
and is
the wait' time device
consumeddevice usage,
usag the task execution time
determined by the task
type of firmware by the task.
The priority in me also gets
S not time critical. execution issuited
suited
placement within the loop, which a task is to
aelay 1s acceptable Typical
in a
for super
examples are electronic embedded devices where
and it will where
response
loop based ex-
aPpicaions demand time critical not create toys and video
gaming response time for
me tor a task
a task

catastrophic. Flight Control systems,


any
operational issues devices. Here any
response to tasks/events and or
potential hazards. Whereasresponse
ces, Nuclear
critical
any
monitoring devices, etc.Airarebag control and Anti Locking
task response. delay in the response may certain
typical examples of Brake (ABS) become
How the
increasing systems for ve-
applications/devices
tions? Well the need
answer is
for time
critical response for demanding time
. ASsign priority to tasks tasks/events is addressed in embedded
2
2. and execute the applica-
3. Dynamically
Schedule change the priorities
high priority task when the
task is
the of tasks if ready to execute.
4. Switch the execution of tasks based on the required on a need basis.
execution of task when priorities.
including
I/O device a task is
waiting for an external event or a
The
introduction of operation. system resource
these needs to a operating system based firmware
greater extent. execution in embedded devices can address
10.1 OPERATING SYSTEM
The
BASICS
operating system acts as a
bridge between
resources through the
and makes them
available
a set of
applications/tasks
system functionalities and services.
user
The OS
and the
underlying system
to the user manages the system
is a collection of
different I/O applications/tasks need basis. A normal
subsystems,
on a resources
operating system is working, and storage memory. The primary computing system
Make the system functions of an
convenient to use
Organise and manage the system resources
Figure 10.1 gives an insight eficiently and
into the basic correctly
with rest of the world. components of an
operating system and their interfaces
10.1.1 The Kernel
The kernel is the of the
core
operating system and is responsible for
the communication among the hardware and other system managing the system resources and
services. Kernel acts as
between system resources and user applications. Kernel the abstraction layer
For a general purpose OS, the kernel contains different contains a set of system libraries and services.
services for handling the
Process Management Process management deals With following.
managing the processes/tasks. Process man-
agement includes setting up the memory space for the proOcess,
ry space, allocating system resources, SCneauing apa managing loading the process's code into the mem-
the execution of the
process, setting
Real-Time Operating System
(RTos) based Embedded
System Design 383
User Applications

Memory management Application


programming
Process management interface (API)
Time management
File system management
I/0 system management

Device driver
Underlying hardware interface
Fig. 10.1 The Operating System Architecture

un and managing the Process Control Block


(PCB), Inter Process Communication and
rOcess termination/deletion, etc. We will look
pro
in a later section of this chapter.
into the synchronisation,
description of process and process management
Primary Memory Management The term
where processes are loaded and variables and primary memory refers to the volatile memory (RAM)
shared data associated with each
Memory Management Unit (MMU) of the kernel is process are stored. The
.Keeping track of which part of the memory area is responsible for
Allocating and De-allocating memory space on a need currently used by which process
basis (Dynamic memory allocation).
File System Management File is a collection
of related information. A file could
(source code or executable), text files, image files, word be a
files differ in the kind of information documents, audio/video files, etc. Each program
of these
file operation is a useful service
they hold and the way in which the
information is stored. The
provided by the OS. The file system management service of Kernel is
responsible for
The creation, deletion and alteration of
files
Creation, deletion and alteration of directories
Saving of files in the secondary storage memory (e.g. Hard disk storage)
Providing automatic allocation of file space based on the amount of free space available
Providing a flexible naming convention for the files
The various file system management operations are OS dependent. For
example, the kernel Micro-
SOrt DOS OSsupports a specific set of file system management operations and they are notof the same
as the file
system operations supported by UNIX Kernel.
O System (Device) Management Kernel is responsible for routing the I/O requests coming from
aterent user applications to the appropriate VO devices of the system. In a well-structured OS, the
direct accessing of I/O devices are not allowed and the access to them are provided through a set of
Pplication Programming Interfaces (APIs) exposed by the kernel. The kernel maintains a list of all
e devices of the system. This list may be available in advance, at the time of building the kernel.
n e kernels, dynamically updates the list of available devices as and when a new device is installed
Embedded Systems
Introduction to
384
is
new plug
'n' play USB device attached o 1.

updated when a
Windows XP kernel keeps the list different Os Kernels) of the kerna
1S(eg.
across
responsibleThe
for service
handling all /O device related
(Name vary
operations.
may The kernel talks to the IVO device throuol.
ce
'Device Manager'
ne system). The devic
service, called drivers.
deviCe
implemented in a
of low-level systems calls, which are Manager is responsible for
a set of devices. The Device
specific to a device or a class
unvers are
Loading and unloading of device drivers control signals to and from the device
ENChanging information and the system specific
management
deals with managing the
The secondary storage
Secondary Storage Managerment Secondary memory is used as
if connected to the system.
Secondary storage memory devices, any, the main memory is volatile. In most of the systems, the
since
ackup medium tor programs and data storage management
service of kernel
The secondary
SCcondary storage is kept in disks (Hard Disk).
deals with
Disk storage allocation
Disk scheduling (Time interval at which the disk is activated to backup data)
Free Disk space management
a way to support
are designed in such
Protection Systemns Most of the modern operating systems
Windows XP with user permissions like
multiple users with ditferent levels of access permissions (e.g.
'Administrator'. 'Standard', "Restricted', etc.). Protection deals with implementing thesecurity policies
or processes or users.
to restrict the access to both and system resources by different applications
user
to view or modify the whole/
In multiuser supported operating systems, one user may not be allowed
not be granted with
portions of another user's data or profile details. In addition, some application may
is the
permission to make use of some of the system resources. This kind of protection provided by
protection services running within the kernel.
Interrupt Handler Kernel provides handler mechanism for all external/internalinterrupts generated
by the system.
These are some of the important services offered by the kernel of an operating system. It does not
mean that a kernel contains no more than components/services explained above. Depending on the type
of the operating system, a kernel may contain lesser number of components/services or more number
of components/services. In addition to the components/services listed above, many operating systems
offer a number of add-on system components/services to the kernel. Network communication, network
management, user-interface graphics, timer services (delays, timeouts, etc.), error handler, database
management, etc. are examples for such components/services. Kernel exposes the interface to the vari-
ous kernel applications/services, hosted by kernel, to the user applications through a set of standard
Application Programming Interfaces (API). User applications can avail these API calls to access the
various kernel application/services.
10.1.1.1 Kernel Space and User Space As
discussed in the earlier section, the
we
applications/
services are classified into two categories, namely: user applications and kernel applications. The pro
gram code corresponding to the kernel applications/services are kept in a contiguous area (OS de
nendent) of primary (working) memory and is protected from the un-authorised access by user pro
grams/applications. The memory space at which the kernel code is located is known as 'Kernel Space
Similarly, all user applications are log2ded to a specime area of primary memory and this memory area
is referred as"User Space. User space is n e area where user
nemory applications are loaded and ex
ecuted The partitioning memory
of into kernel and user space is purely Operating System dependent.
Real-Time Operating System
(RTos) based Embedded
System Design
ome OS implements this kind of 385
nd user application code partitioning and protection whereas
kern

ciuDDOrt, the
storage into two some OS do
segregate the not
nemory support, user
applications separate areas. In an
are loaded
operating
chnique; Meaning, the entire codeinto its corresponding virtual system with virtual
demand paging tech
mary) memory at once, instead the user for the user memory space witn
main
pagesare oaded into and out of the main
application need
application code is split into not be loadedto the
af the
and out of main memory 1S memory area on a need basis. The
different pages and these
termed as act of
emory and seco condary storage memory. Swapping'. Swapping happens betweenloading
Each the
the code into
allowedaccessingthe memory space process run in its own virtual main (primary)
the process. Each corresponding another processes, unless
process will have certain to memory space and are not
uased on the privilege settings, processesprivilege levels on accessing the explicitly requested
rec by
memory of other
ar share through some other can
request kernel to map another processes
dein main memory and it is not mechanism. Most of the process's memory to its
operating
swapped out into the secondary systems keep the kernel
1011.2 Monolithic Kernel and memory.
application
Microkernel As we know, the kernel
erating svstem. Different approaches are
adopted for building an Operating fornms the heart of an op-
o

nel design, kernels can be classified into System kernel. Based on the
'Monolithic' and 'Micro'.
Monolithic Kernel In monolithic kernel
Here all kemel modules run within the same architecture, all kernel services run in the kernel space.
nal integration of kernel modules in memory space under a single kernel thread.
monolithic kernel architecture allows The tight inter-
low-level features of the underlying system. The the effective utilisation of the
or failure in any one of the kernel major drawback of monolithic kernel is that
modules leads to the
crashing of the entire kernel application.any
error
SOLARIS, MS-DOS kernels
examples
are of monolithic kernel. The architecture LINUX,
monolithic kernel is given in Fig. 10.2. representation of a

Applications

Monolithic kernel with all


operaing system services
running in kemel space

Fig. 10.2 The Monolithic Kernel Model

Microkernel The microkernel design incorporates only the essential set of


Operating System ser-
CS into the kernel. The rest of the Operating System services are implemented in programs known
ervers which runs in user space. This provides a highly modular design and OS-neutral abstrac-
tion ne kernel. Memory management, process management, tumer systems_and interrupt handlers
Systems
386 Introduction to Embedded

are the essential services, which forms the part ol


the microkernel. Mach, QNX, Minix 3 kernels are Servers (kernel
examples for microkernel. The architecture repre- services running
Applications
sentation ofa microkernel is shown in Fig. 10.3. in user space)
Microkernel based design approach offers the
following benefits
Robustness: If a problem is encountered in
any of the services, which runs as "Server
application, the same can be reconfigured Microkernel with essential
and re-started without the need for re-start- services like memory
ing the entire OS. Thus, this approach is
management, process
highly useful for systems, which demands management, timer system, etc..
high 'availability'. Refer 3 to get
Chapter
an
understanding 'availability'.
of Since the
services which run as 'Servers' are running
The Microkernel model
on a different
memory space, the chances
Fig. 10.3
of corruption of kernel
services are ideally
zero.
Configurability: Any services, which run as "Server' application can be changed without the ned
to restart the whole
system. This makes the system dynamically configurable.

A0.2
A0.2 TYPES OF OPERATING SYSTEMS
Depending on the type of kernel and kernel services, purpose and type of computing systems where the
OS is
deployed and the responsiveness to applications, Operating Systems are classified into different
types
10.2.1 General Purpose Operating System (GPOs)
The operating systems, which are deployed in general computing systems, are
pose Operating Systems (GPOS). The kernel of such referred as General Pur-r
of services required for an OS is more generalised and it contains all kinds
executing generic applications. General-purpose operating systems are often
quite non-deterministic in behaviour. Their services can inject random delays into application software
and may cause slow responsiveness of an
application unexpected times. GPOS are usually deployed
at
incomputing systems where deterministic behaviour is not an
Desktop system is a typical example for a system where GPOSs importantcriterion. Personal Computer/
etc. are examples for General
Purpose Operating Systems.
are
deployed. Windows XP/MS-DOS

10.2.2 Real-Time Operating System (RTOS)


There is nouniversal definition available for the term °Real-Time' when it
operating systems. What "Real-1ime means in Operating System context isisstill used in conjunction with
a debatable topic and
there are many definitions available. In a broad sense,
iour, Deterministic timing behaviour in "Real-lime' implies deterministic timing behav-
RIOS contExt means the OS services consumes only known and
expected amounts of time regardless the number of services. A Real-Time
implements policies and rules concerning time-critical allocation of a Operating System or RTOS
system's resources. The RTOS
Real-Time Operating System (RTOS)
based
Embedded System Design
387
ecides which appliolications should run in which order
edictable performance is the hallmark and how much time needs to be allocated for each
lication. Pred
by tn
lication of policies
sistent applic
e nolicies and resolve policy and rules.
of
Policies well-designed RTOS. Thisallois best achieved
a

ment
conflicts. Windows guide the design of an RTOS. Rules
of Real-T
Operating Systems (RTOs). CE, QNX, VxWorks imple-
examples

10.2.2.1 The Real-Time Kernel


MicroC/OS-II, etc. are
ernel. In complement to the conventional The kernel of a Real-Time
Operating System is referred as Real.
OS kermel, the Real-Time
antains only the minimal Set of kernel is highly
specialised
hasic functions services required for running the
of a Real-lime kernel are listed below: user
applications/tasks. The
.Task/Process management
. Task/Process scheduling
.Task/Process synchronisation-
.Error/Exception handling
Memory managenment.
.Interrupthandlinng
.Time management
Task/Process management Deals with setting up the memory space for the tasks, loading the
task's code into the memory space, allocating system resources,
setting up a Task
for the task and task/process termination/deletion. A Task Control Block (TCB) isControl
used forBlock (TCB)
holding the
information corresponding to a task. TCB usually contains the following set of information.
Task ID: Task Identification Number
State: The current state of the task (e.g. State= "Ready' for a task which is ready
to execute)
Task Type: Task type. Indicates what is the type for this task. The task can be a hard real time or soft real
time or background task.-
TaskPriority: Task priority (e.g. Task priority = 1 for task with priority = 1)

Task Context Pointer: Context pointer. Pointer for context saving


Task Memory Pointers: Pointers to the code memory, data memory and stack memory for the task
Task System Resource Pointers: Pointers to system resources (semaphores, mutex, etc.) used by the task
Task Pointers: Pointers to other TCBs (TCBs for preceding, next and waiting tasks)
Other Parameters Other relevant task parameters
The parameters and implementation of the TCB is kernel dependent. The TCB parameters vary across
different kernels, based on the task management implementation. Task management service utilises the
TCB of a task in the following way
task creating a task
Createsa TCB for a on
task is terminated or deleted
Delete/remove the TCB of a task when the
Reads the TCB to get the state of a task
need basis (e.g. on a context switch)
Update the TCB with updated parameters
on

task dynamically
Modify the TCB to change the priority ofthe
various tasks/processes. A kernel
Task/Process Scheduling sharing the CPU among
Deals with
scheduling. Scheduler is nothing but an algorithm imple
application called 'Scheduler handles the task deterministic
scheduling of tasks to provide a
efficient and optimal
cnlation, which performs the in a later section of this chapter.
DCnaviour. We will discuss the various types of scheduling
Embedded Sy.
Introduction to

388
the concurrent acces of
Deals with synchronisingbetween various tasks, W reso
Task/Process Synchronisation
which is shared
red across multiple tasks and the
communication
communication in a
Ne will disc
later
SOUrCe
anous synchronisation techniques and intertask
/process
ection of this
chapter.
and handling the errors occurred/e.
Error/Exception Handling Deals with registering deadlocks, deadline ppiuons
raised durin the execution of tasks. Insufficient memory, timeouts, of b
etc. are examples errors/exceptione
error, divide by zero, unknown instruction execution,
task level. DeadioCk 1S an example forE Errors/
CCpuons happen at the kernel level services or at
can

exception, whereas timeout is an example for a task level exception. The OS


kernel gives theeve kemel\
error in the form ofa system call (API). GetLastErrort) APl provided by Winda
tion about the
fi.ws
RTOS is an example for such a system call. Watchdog timer is a mechanism for handling the will CE
for tasks. Certa tasks may involve the waiting of external events from devices. These tasks
infinitely when the external device is not responding and the task willgenerate a hang-up behaviour
order to avoid these proper timeout mechanism should be implemented, A T
types of scenarios, watch
dog is normally used in such situations. The watchdog will be loaded with the maximum expected
time for the event and if the event is not triggered within this wait time, the same is infomed to the tha wait
and the task is timed out. If the event happens before the timeout, the watchdog is resetted. task
Memory Management Compared to the General Purpose Operating Systenms, the memory manaes
ment
function of an RTOS kernel is slightly different. In general, the memory allocation time increases
depending on the size of the block of memory needs to be allocated and the state of the alocatd
memory block (initialised memory block consumes more allocation time than un-initialised memoy
block). Since predictable timing and deterministic behaviour are the primary focus of
an RTOS, RTOS
achieves this by compromising the effectiveness of memory allocation. RTOS makes use of 'block
based memory allocation technique, instead of the usual dynamic memory allocation techniques
by the GPOS. RTOS kernel uses blocks of fixed size of dynamic memory and used
a task on a need the block is allocated for
basis. The blocks are stored in a Free Buffer Queue'. To achieve predictable timing
and avoid the timing overheads, most of the RTOS
kernels allow tasks to access any of the
blocks without any memory memory
protection. RTOS kernels assume that the whole design is proven correct
and protection is unnecessary. Some commercial
RTOS kernels allow memory
and the kernel enters a fail-safe mode when an protection as optional
A few RTOS kernels
illegal memory access occurs.
implement Virtual Memoryî concept for memory allocation if the system
ports secondary memory storage (like HDD and FLASH memory). In the "block' based sup-
location, a block of fixed memory is always allocated for tasks on need memory a
Hence, there will not be any memory fragmentation issues. The basis and it is taken as a unit.
memory allocation can be implemented
as constant functions and thereby it consumes fixed amount of time
the deterministic behaviour of the RTOS kernel for memory allocation. This leaves
garbage collection overhead also. (We will exploreuntouched.The block memory concept avoids the
this technique under the inaMicroC/OS-IT kermel
t Virtual Memory is an imaginary memory supported by certain
operating systems. Virtual memory
able to a task beyond the actual physical memory (RAM)
supported by the system. Virtual expands the address space ava
Memory Management Unit (MMU) and "memory paging. The program memory is implemented with the help ol
memory for a task can be viewed as
page corresponding to a piece of code tnat different pages and
neceas to De exCeuted is
loaded into the main
physical
is no longer required, it is moved out to secondary stOrage
memory and another page which memory (RAM). VWhen a memory pas
laaded into the main memory. This memory movement technique is contains the code snippet to be executed
known as demand
and converts the virtual address of a location in a page to corresponding paging. The MMU handles the demand pag
physical address in the RAM.
Real-Time Operating System (RTOS)
based Embedded
System Design 389
he
block
latter chapter).The based memory
latter ice of memory allocation achieves
imited choice chunk size and deterministic behaviourwith
with the trade-o
trade-of
suboptimal memory
Handling Deals with the handling of various usage.
Intehaviour to systems. Interrupts inform types of interrupts.
Interrupts
immediate attention of the CPU. processor that an external device or provide
Time
task requires the Real
res immed

which ooccurs in sync with the


Interrupts which Interrupts can be either Synchronous or associatea
an

software interrupts fall under Currently


Usually the softwar executing task is known as Synchronous AsynchrooS
the
Synchronous Interrupt categor iide by interrupIs.
ntation error, etc. are examples of synchronous
interrupts. zero, memor
runs inthe same context of the For syncl1ronnus interrupts, the inter-
rupt handler interrupling
hich occurs at any point or task. Asynchronouous interrupts are interrupts,
execution any
or
The interrupts generated by external devices
task, and
are not in
sync with the currently executing tas.
(by asserting the interupt line of the processor/controlle
to which the interrupt
line of the device is
A interrupts, serial data reception/ connected) connected to the processor/controller, timer ove"
transmission interrupts, etc. are examples for asynchronous inter-
rupts. For asynchronous interrupte, the interrupt
handler is usually written as separate task (Depends
an OS kernel implementation) and it runs in a different context.
Hence, a context switch happens while
handling the asynchronous interrupts. Priority levels can be
munts can be enabled or disabled individually, Most of the RTOS assigned to the interrupts and each inter
kernel implements 'Nested interrupts
architecture. Interrupt nesting allows the pre-emption (interruption) of an Interrupt Service Routine
ASR), servicing an interrupt, by a high priority interrupt.
Time Management AcCurate time management is essential for providing precise time reference for
all applications. The time reference to kernel is provided hy a
high-resolution Real-Time Clock (RTC)
hardware chip (hardware timer). The hardware timer is programmed to interrupt the
processor/control-
ler at a fixed rate. This timer interrupt is referred as Timer tick. The Timer tick is taken as the
timing
reference by the kernel. The "Timer tick' interval may vary depending on the hardware timer.
the Timer tick varies in the microseconds range. The time parameters for tasks are expressed as the
Usually
multiples of the "Timer tick.
The System time is updated based on the Timer tick. If the System time register is 32 bits wide and the
Timer tick interval is I microsecond, the System time register will reset in
232 10-6/ (24 * 60 * 60) = 49700 Days ~ 0.0497 Days = 1.19 Hours

Ifthe Timer tick' interval is I millisecond, the systei. I iac register will reset in
232 * 10-3/(24 * 60 60)= 497 ivays = 49.7 Days =~50 Days

The 'Timer tick' interrupt is handled by the Timer Interrupt' handler of kernel.The Timer tick' interrupt
can be utilised for implementing the following actions.
.Save the current context (Context of the currently executing task).
Increment the System time register by one. Generate timing error and reset the System time regis-
ter if the timer tick count is greater than the maximum range available for System time register.
Update the timers implemented in kernel YIncrement or decrement the timer registers for each
timer depending on the count direction setting for each register. Increment registers with countdi
rection setting = "count up' and decrement registers with count direction setting = 'count down').

Activate the periodic tasks, which are in the id'e state.


Invoke the scheduler and schedule the tasiks again based on the scheduling algorithm.
Delete all the terminated tasks and their associated data structures (TCBS)
Load the context for the first task in the ready queue. Due to the re-scheduling, the ready task might
be changed to a new one from the task, which was preempted by the Timer Interrupt' task.
Embedded Systems
Introduction to
390
other functionalities also (Eva..

>cting mplesequi
are
functions, some RTOS provide
Apart from these basic options for selectir
and network functions). Some RTOS kernel provides
anagement The user can pick
the required functione
tions at the time of building a kernel.
same to generate
the kernel binary. Windows CE i a Om the se
oavailable functions and compile the
ample for such an RTOS. While building the target, the user
can select the required com typicalf e
components
kernel. the
10.2.2.2 Hard Real-Time Real-Time Operating Systemsthat strictly adhere to the ti
Straints for a task is referred as 'Hard Real-Time' systems. A Hard Real-1ime system must
deadlines for a task without any slippage. Missing any deadline may produce catastrophie
phic results
meet the
Hard lose and irrecoverable
Real-Time Systems, including permanent data damagesto thesystem
Hard Real-Time systems emphasise the principle 'A late answer is a wronganswer.Asystem
em can ha
Several such tasks and the key to theircorrect operationlies in scheduling them so that they meet
me constraints. Airbag control systems and Anti-lock Brake Systems (ABS) of vehiclesare h
examples for Hard Real-Time Systems. The Air bag control system should beinto action and deploud typica
air
bags when the vehicle meets a severe accident. Ideally speaking, the time ror
deployment task, when an accident is sensed by the Air bag control triggering the ar o
bags should deployed exactly within the time frame,
be system, should be zero and the ae
Any delay in the deployment of the air bags makeswhich
is
task,
the life
predefined for the air bag deployme
the air
deployment task is triggered, the currently executing of
bag the passengers under threat. When
task must be
deployment task should be brought into execution, and the necessary I/O systemspre-empted, the air bao
task. To meet the strict deadline, the timeshould made read.
ily available for the air bag be
deployment between the air bag
deployment event triggering and start of the air
ally zero. As a rule of thumb, Hard Real-Time bag deployment task execution should be
for handling the Systems does not implement the virtual minimum, ide
memory. This eliminates the delay in memory model
task to and from the swapping in and out the code
primary of Human in the corresponding the
In general, the to
introduces unexpected delays memory. presence
and does not contain a
in the task execution.
Most of the Hard Real-Time loop (HITL) for tasks
'human in the loop. Systems are automatic
10.2.2.3 Soft Real-Time
Real-Time Operating System that
but offer the best effort to meet the does not
deadline referred as Soft Real-Time'guarantee meeting deadlines,
for tasksare
acceptable for a Soft Real-timearesystem if the systems. Missing deadlines
compliance limit
late answer is an
of the Quality of Service (QoS). A Soft frequency of deadline
missing is within the
acceptable answer, it could have done bit Real-Time system emphasises the principle
ten have a
'human in the loop (HITL).butAutomatic faster'. Soft Real-Time systems most or-
Real-Time System. If the ATM Teller Machine (ATM) is a
takes a few seconds more than the typical example for Sott
happens. An audio-video playback ideal
damage arises if a sample comes latesystem is another operation time, nothing tatal
by fraction of a example
for Soft
second, for playback.Real-Time system. No potentia
10.3 TASKS, PROCESS AND
THREADS
The term 'task' refers to
something
execution of a number of tasks.
that needs
to be done. In our
assigned by day-to-day
The
task can be the one life, we are bound ton
orderprofessors/teachers
our or the one related to our our
of priority and managers or the one assigned
personal or family needs.
schedule/timeline for In addition, we
program in execution and executing
is defined as the these tasks. In will have a
the related the operating
information maintained bysystem context, a ta
the operating
ting system
syste
Real-Time Operating System
(RTOS) based Embedded
System Design 391
he program. Task 1S also
known as
'Job' in
also called a
is also
execution is "Process. The terms the operating system context. A
operating syste contex and nmost often *Task', Job' and Process' refer program or part of it
in
they are used to the same
entity
10.3.1 Process
interchangeably. in the

Process' is a program, or part of it, in


Necution. Multiple instances ot the sameexecution. Process is also known an instance of a
as
ous svstem resources like CPU for program can execute
simultaneously. A process
program in
executing process, memory for
the nrocess and associated variables, the requires var-
1/0 devices for storing the code corresponding to
in execution. information exchange, etc. A is process sequential
10.3.1.1 The Structure of a Process The concept of
nseudo parallelism) of tasks and 'Process' leads to concurrent execution
i
thereby the efficient utilisation of the CPU
Concurrent execution is achieved through the
sharing of CPU
and other system resources.
processor in properties and holds a set of among the processes. A process mimics
registers, process
the next executable instruction of the process, a stack for status, a Program Counter (PC) to point to
Drocess and the code corresponding to the holding the local variables associated with the
process. This can be visualised as shown in
Fig. 10.4.

Process

Stack
(Stack pointer)
Working registers
Status registers

Program counter (PC)

Code memory
corresponding to the
Process

Fig. 10.4 Structure of a Process

A process which inherits all the properties of the CPU can be considered as a virtual processor, await-
When the process gets its turn, its
1ng its turn to have its properties switched into the physical processor.
the physical registers of the CPU. From
registers and the program counter register becomes mapped to
into three regions, namely,
perspective, the memory occudied by the process segregated
is
a memory
Stack memory, Data memory and Code memory (Fig. 10.5).
variables local to the process. Data memory
he Stack' memory holds all temporary data such as cor
nolds all global data for the process. The code memory
contains the program code (instructions)
area of memory 1s
to the On loading a process into the main memory, a specific
TCsponding process.
starts (OS Kernel implementation dependent)
at
a t e d for the process. The stack memory usually
392 Introduction to Embedded Systems

C highest memory address from the memory area allocatea 101


ne process. Say for example, the memory map of the memory Stack Memory
ao
alocated for the process is 2048 to 2100, the stack memory
stars a
ressTO0 and grows downwards to accommodate the variabies Stack memory| grows
local to the downwards
process.
.3.1.2
Ora
Process States and State Transition The
ereation Data memory Tgrows
process to its termination is not a upwards
process traverses through a series of statessingle step operation. I ne
during its transition from
thenewly created state to the terminated state. The cycle througn
which a
process changes its state from
Tion completed is known as Process Life'newly created
to 'execu-
Data Memory
through which a process traverses Cycle. The various states
Cyele indicates the current through during a ProcesS Lie
of the
status with respect to time
and also
provides information on what itprocess
is allowed to do next. Fig
Code Memory
ure 10.6
represents the various states associated with a
The state at
which a process is created
process. Fig. 10.5 Memory organisationa
Created State'. The being is referred as of a Process
Operating System recognises a process in the
Created State'
but no resources are
allocated to
the process. The
ed into the
state, where a
process is incept-
time for
memory and awaiting the processor Created
execution, is known as 'Ready
At this
stage. the process is placed in the State'.
list queue maintained by the OS. The state 'Ready
where Incepted into memory
in the source code instructions
process is being executed is corresponding
the to

State'. Running state is the called Running


state at which the
process execution happens. 'Blocked
State/Wait IO Completion Ready
State refers to a state where a running process
S h a r e dR e s o u r c e A c q u i r e d

is
temporarily suspended from execution and
does not have immediate access to resources. The
blocked state might be invoked by various condi- Blocked
tions like: the
process enters a wait state for an
event to occur
(e.g. Waiting for user inputs such
as
keyboard input) or waiting for getting access
to a shared resource
Waiting Waifor tiShared
ng for VO
(will be discussed at a later
section of this chapter). A state where the Resource Running
process
completes its execution is known as 'Completed
State. The transition of a
process from one state ExecutionCompletion
to another is known as 'State
transition'. When a
process changes its state from Ready to running
or from
unning to blocked or terminated or from
blocked to running, the CPU allocation for the Completed
process may also change:
It should be noted that the state representation Fig. 10.6 Process states and state transition
for a process/task mentioned here is a generic representation
rep-
Real-Time Operating
System (RT ) based
ntation. The states associated with Embedded Syste Design
res 393
or number states than
of task a
may be known with
Works' kemel. the tasks maythebe one explained here under different name or there a
may be more
hET AY and SUSPEND.
in either
The PEND state one or a specific
different OS kernel For
combination example, under
n for L O or
system resource The DELAYrepresents a state where the of the states READY, PEND,
andnd the SUSPEND state state
represents a state in which the task/process
is blocked on
wait-
represents a state
where
process is ternporarily task/process is sieeping
fson and not
available
for
Under Micro exccution
a task/

pORMANT. READY. RUNNING, WATTING OS I1 kernel the suspended from execu-


tasks may be
thc 'Created' state and WATTING state or
INT ERRUPTED The
in
the
one of states,
ar O represents the state
access. We w1ll diseuss about the states and in
DORMANT state represents
which a process waits for
I1 kemel n a later chapter state transition for tasks under
shared resource
VxWorks and uC/OS-
20.3.1.3 Process Management Process management deals
up the memory for space the with the creation of
process, loading the process's code into a process, setting
tem resources, setting
up a Process Control Block the memory
tnon. For more details on Process (PCB) for the process and space, allocating sys
process
Management, refer to the section 'Task/Process termination/dele-
under the topic "The Real-Time Kernel' managernent' given
of this chapter.
10.3.2 Threads
Stack memory for Thread 1
A thread is the primitive that can execute
code.
A thread IS a single
sequential flow of control Stack memory for Thread 2 Stack Memory
within a process. Thread is also known as
light- for Process
weight prOcessA process can have many threads
of execution. Different threads, which are
part of
a process, share the same address
space; meaning
they share the data memory, code memory and Data memory for process
heap memory area. Threads maintain their own
thread status (CPU register values), Program Code memory for process
Counter (PC) and stack. The memory model for
a process and its associated threads are given in Fig. 10.7 Memory organisation of a Process and its
Fig. 10.7. associated Threads

10.3.2.1 The Concept of Multithreading A process/task in embedded application may be a com-


plex or lengthy one and it may contain various suboperations like geting input from 1/0 devices con-
nected to the processor, performing some internal calculations/operations, updating some 1o devices
ce1 all the subfunctions of a task are executed in sequence, the CPU utilisation may not be etficient.
ror example, if the process is waiting for a user input, the CPU enters the wait state for the event, and
the process execution also enters a wait state. Instead of this single sequential execution of the whole
out the ditferent subfunctionalities of
process, if the task/process is split into different threads carrying
the thread corresponding to the /O opera-
the process, the CPU can be effectively utilised and when the I'O event for their operation can
be
O n enterS the another threads which do not require
wait state,
eficient utilisation
process and the
into execution. This Icads to more speedy execution ofthe
Cnea architecture of a process can be
better visualised
time and resources. The mulithreaded
C processor
with the thread-process diagram shown in Fig. 10.8.
394 Introduction to Embedded Systems

Task/Process

Code memory

Data memory

Stack
Stack Stack

Registers Registers Registers

Thread Thread 2 Thrcad 3


roid main (void) int ChildThread int Chi ldThread2
(void) (void)
/Create child
//Do somet hing
thread1 //Do something
CreateThread (NULL,
1000, (LPTHREAD_STA
RT_ROUTINE)
ChildThread 1, NULL,
0, &dwThreadID )
/Create child
thread 2
CreateThread (NULL,
1000, (LPTHREAD_STA
RT_ROUTINE)
ChildThread 2, NULL,
0, &dwThreadIb);

(Fig. 10.8 Process with multi-threads

If the process is
split into multiple threads, which executes a portion of the
main thread and rest of the threads will be created within process, there will be a
the main thread. Use of
execute a process brings the following advantage. multiple threads to
Better memory utilisation. Multiple threads
of the same process share the address space for data
memory. This also reduces the complexity of inter thread
sharedacross the threads communication since variables can be
Since the process is split into different thréads, when
thread enters a wait state, the CPU
one
be utilised by other threads of the process that do not can
require the event, which the other thread is
waiting,
for processing. This speeds up the execution of the process.
.Efficient CPU utilisation. The CPU is engaged all time
0.3.2.2 Thread Stardards : Thread standards deal with the
different standards
"eation and management. These standards are utilised by the available for thread
read It is
operating systems for thread creation and
management. a set of thread class libraries. 1he
commonly available thread class libraries
explained below.
Real-Time Operating System
(RTOs) based
ased Embed Embedded
ded System Design
IN
POS Threads POSIX
stands for Portable 395 Design
h the
with Real-Time extensions and POSIX 4aOperating System Interface.
ibrary
dard library for
for thread creation standard deals with The POSIX.4
standaru
POSIX thread creation and
and
management is 'Pthreads'. thread extensions. The POSIX dealsstan-
The pnmitive management functions in 'C" Pthreads library defines the set of
langua
guage
snt
pthread create
(pthread t *new thread 1D,
oid start function) const
argument s) ; pthread attr t attribute,
(void *), void
create a new thread for
running the
created thread and function start
function. Here pthread t is the
pthread_attr_t s the data
type for handle to the newly
the functhon the thread is going to execute
and holding
the thread attributes.
'start function'
is
avondin the above On successful arguments is the arguments for
example). 'start
pthread createl) function'
Thread Control Block ereation of a Pthread, (lt is
(mewthread_ID in our(OCB)corresponding associates the
to the
example). newly created thread to the variable of type pthread
The prmitive i

int pthread join (pthread _t new thread,


void thread status)
blocks the current thread and waits
until the
mew_thread) completion of the thread
pointed by it (In this example
POSIX "thread calls' returns an
All the
It is always good to check the returm integer. A return value of zero indicates the success
value of each call. of the call.

Example 1
Wite a multithreaded application to print "Hello I'm in main
thread" from the main thread and "Hello l'm in
5tames each, using the new thread"
pthread_create) and pthread_join) POSIX primitives.
/Assumes the application is running on an os where PoSIX 1ibrary is
available
include <pthread.h>
include <stdlib.h>
include <stdio.h>
*****

I/ew hread function for


printing "Hello I'm in new thread"
voidnew_thread( void *thread_args )

0: 5 j+)
printf(Hello I'm in new thread\n" )
/hait for some time. Do nothing
/2he toliowing line of code can be replaced with
9 s supported delay function 1ike sleep( ) , delay () etC.
fori- 0: i < 10000; i t )
Ieturn NULL;
396 Introduction to Embedaded Systems

* * * ** **** ******
//***************:
/Start of main thread
intmain( void )

int i, j:
pthread_t tcb;
//Cedte the new thread for executing new thread tunction
pthread_create ( &tcb, NULL, new thread, NULI ))

//New thread creation failed


printf ("Error in creating new thread\n" )i
return -1;

for j= 0; j < 5; jt+ )


printf ("Hello I'm in main
/Wait for
thread \n" );
some time. Do nothing
/The
following line of code can be replaced delay
withn
/oS supported delay function 1ike sleep () etc..

for i= 0; i < 10000; it+ );

if
(pthread_join (tcb, NULL ))

//Thread join failed


printf ("Error in Thread join\n" );
return -1;

return 1;

You can compile this


application using the gcc compiler. Examine the output to figure out the thread execution switch-
ing. The lines printed will give an idea of the order in which the thread
execution is switched between. The
call forces the main thread to wait until the pthread_join
The termination of a thread can
completion of the thread tcb, if the main thread finishes the execution first.
happen in different ways. The thread can terminate either by completing its execu-
tion (natural termination) or by a forced termination. In a
natural termination, the thread
returns back to the main thread completes its execution and
through simple
a return or by executing the pthread_exit) call. Forced termination
can be achieved by the call
pthread_cancel) or through the termination of the main thread with exit or exec functions.
pthread_cancel) call is used by a thread to terminate another thread.
pthread_exit() call is used by a thread to explicitly exit after it completes its work and is no longer
If the main thread finishes before the threads it has created, and exits with required to exist.
pthread_exit(), other threads continue to
execute. If the main thread uses exit call to exit the thread, all threads created
the
by the main thread is terminated forcefully.
Exiting a thread with the call pthread_exit) will not perform a cleanup. It will not close
and files will remain in the open status even after the thread terminates. any files opened by the thread
Calling pthread join at the end of the main thread
is the best way to achieve synchronisation and proper cleanup. The main
thread, after
finishing call, the main thread
its task waits for the
completion of other threads, which were joined to it using the pthreadjoin call. With a pthread_join
waits other threads, which were joined to it, and finally merges to the
single main thread. If a new thread spawned by the
main thread is still not joined to the main thread, it will be counted against the system's maximum
cleanup will lead to the failure of new thread creation.
thread limit. Improper
Real-Time Operating System (RTOS) based
Embedded System Design 397
Win32 Threads Win32 threads are the threads
supported by various flavours of Windows
s Win32 Application Programming Interface
The Operating
(Win32 API) libraries provide the standard
n32 thread creation and management functions. Win32 threads
set
are created with the API
DIE CreateThread (LPSECURITY_ATTRIBUTES
LPTHREAD_START_ROUTINE lpThreadAttributes,
lpstartAddress, LPVOID lpParameter,DWORD
dwStack-
ationFlags, LPDWORD lpThreadId ): DWORD dwCre-
The parameter lpThreadAtributes defines the
security attributes
as the stack size for the thread. These two parameters are not for the thread and dwStackSize de-
supported by the Windows CE Real-
Time Operating Systems and it should be kept as NULL and 0 respectively in a Create Thread API Call.
are
The other parameters
nStartAddress: Pointer to the function which is to be executed by the thread.
loParameter: Parameter specifying an application-defined value that is passed to the thread routine.
he CreationFlags: Defines the state of the thread when it is created. Usually it is kept as 0 or CRE-
ATE SUSPENDED implying the thread is created and kept at the suspended state.
IpThreadld: Pointer to a DWORD that receives the identifier for the thread.
On successful creation of the thread, CreateThread returns the handle to the thread and the thread identi-
fier.
The API GetCurrentThreadfvoid) returns thehandle ofthe currentthreadand
GetCurrentThreadld(void)
returns its ID. GetThreadPriority (HANDLE hThread) API returns an integer value representing the cur-
rent priority of the thread whose handle is passed as hThread. Threads are always created with normal
priority (THREAD_PRIORITY_NORMAL. Refer MSDN documentation for the different thread pri-
orities and their meaning). SetThreadPriority (HANDLE hThre.ad, int nPriority) API is used for setting
the priority of a thread. The first parameter to this function represents the thread handle and the second
one the thread priority.
For Win32 threads, the normal thread termination happens when an exception occurs in the thread,
or when the thread's execution is completed or when the primary thread or the process to which the
thread is associated is terminated. A thread can exit itself by calling the ExitThread (DWORD dwEr
itCode) API. The parameter dwExitCode sets the exit code for thread termination. Calling ExitThread
API frees all the resources utilised by the thread. The exit code of a thread can be checked by other
threads by calling the GetExitCodeThread (HANDLE hThread, LPDWORD IpËxitCode). Terminate
Thread (HANDLE HThread, DWORD dwExitCode) API is used for terminating a thread from another
thread. The handle hThread indicates which thread is to be terminated and dwExitCode sets the exit code
for the thread. This API will not execute the thread termination and clean up code and may not free the
resources occupied by the thread. Terminate Thread is a potentially dangerous call and it should not be
used in normal conditions as a mechanism for terminating a thread. Use this call only as a final choice.
SuspendThread(HANDLE hThread) API can be used for suspending a thread from execution provided
the handle hThread possesses THREAD_SUSPEND_RESUME access right. If the SuspendThread API
call succeeds, the thread stops executing and increments its internal suspend count. The thread becomes
Suspended if its suspend count is greater than zero. The SuspendThread function is primarily designed
for use by debuggers. One must be cautious in using this API for the reason it may cause deadlock condi-
tion if the thread is suspended at a stage where it acquired a mutex or shared resource and another thread
tries to access the same. The ResuneThread(HANDLE hThread) API is used for resuming a suspended
thread. The ResumeThread API checks the suspend count of the specified thread. A suspend count of
398 Introduction to Embedded Systems

zero indicates that the specified thread is not currently in the suspended mode. if the count is not.
the count is nented by one and if the resulting count value is zero, the thread is resumed
APLSeep (DWORD dwMilliseconds) can be used for suspending a thread for the duration specified The
in
miuiseconds by the Sleep function. The
Sleep call is initiated by the
thread.
specified in
Example 2
write a multithreaded application using Win32 APIs to set up a counter in the main thread and secondary thread to co
rom O to 10 and print the counts from both the threads. Put a delay of 500 ms in between the successive printing incount
hoh
the threads.

#include "windows.h"
#include "stdio.h"
7* * * * * * * * * * * * **** ** * ** * * * * ** ***** *** * * ** t * * * * * * * * * * * * * * * * * * * * * * *

//Child thread
7** ************* ******** ** * **** ** ** *******
***** *****************x**
void ChildThread (void)

char ii
for (i=0; i<=10;++i)

printf ("Executing Child Thread: Counter =


%d\n",i) ;
Sleep (500);

* * **** * ** * **** **** ** * * *** * * ** * * * ** * *


** * * * * * * * * * * *** ** **** **** * *
//Primary thread
* * * * * k * ** k * *** ** * * **** *** * *** * * ** * * * * * * * ** *** *

int main (int argc, char* argv [])


HANDLE hThread;
DWORD dwThreadI D;
char i;
hThread=CreateThread(NULL,1000, (LPTHREAD_START ROUTINE)
ChildThread, NULL, 0, &dwThreadID) ;
if (hThread==NULL)

printf("Thread Creation Failed\nError No


sdn",GetLastError ());
return 1;

for (i=0;i<=10; ++i)

p r i n t f ("Executing Main Thread: Counter = %d\n", i)

Sleep(500)
return 0;
Real-Time Operating System
(RTOS) based Embedded
System Design 399
To execute this program, create a new
Win32 Con-
sole Application using Microsoft Visual
C+and add
the above piece ot code to it and
compile. The output
D:IVCThreadDebugThread.ex
Mecut ing -E
abtained running this application on a machine with
on Execut ing Main
ChildThread: Counter
Theead: Counter
XOcut ing Main Thread:
Windows XP operating system is given in Fig. 10.9, Execut ing Chi ld Thread: Count
If vou examine the output. you can see the XeCut ing Counte
switching xecuting Main
Child Thread:
Thread: G0unter
hetw cen main and child threads. The Execut ing Child Thread: Counter
output need not be EXecut ing Ma in Counter
the same always. The output is purely
dependent on the xecut ing ChildThread:
The ad:
Counter
EXeCut ing Hain Threads 0Unter
scheduling policies implemented by the windows op- Execut ing Chi ld Thre ad: Counter
Counter
erating system for thread scheduling. You may get the
Execut ing Main Thread: ounter
Execut ing Child Thread: Gounter '
output or a different output cach time Execut ing
Execut ing hain
same Thread C0unter
you run the
application Execut ing Child Thre ad: Counter
Ma in Thread:
Execut ing Main Thread: Counter
Counter
Execut ing Child Thre ad:
Tava Threads Java threads are the threads Executing Main Counter
Execut ing Child Thread
Thre ad: Counter
supported by Java
programming Language. Execut ing Main Thread: Counter
Execut ing Child Thread: Counter
The java thread class Thread' is
defined in the Press any key to cont
inue
package java.lang. This package needs to be
imported for using the thread creation functions
supported by the Java thread class. There are Fig. 10.9 Output of the Win32 Multithreaded
two ways of creating threads in Java: Either application
by
extending the base "Thread class or by
implementing an interface. Extending the thread class allows
inheriting the methods and variables of the parent class
(Thread class) only whereas interface allowssa
way to achieve the requirements for a set of classes. The
following piece of code illustrates the imple-
mentation of Java threads with extending the thread base class Th ead.
import java.lang.*;
public class MyThread extends Thread

public void run ()

System.out .println ("Hello from MyThread !") ;

public static void main (String args[])

(new MyThread ()).start ();

The above piece of code creates a new class MyThread by extending the base class Thread. It also
Overrides the run) method inherited from the base class with its own run() method. The run() method
of MyThread implements all the task for the MyThread thread. The method start() moves the thread to
a
pool of threads waiting for their turn to be up for picked
the
execution by scheduler.
The
thread is said
to be in the Ready' state at this stage. The scheduler picks the threads for execution from the pool based
on the thread
priorities.
B.g. MyThread.start();
he output of the above piece of code when executed on Windows XP platform is given in

Fig. 10.10.
400 Introduction to Embedded Systems

C:SYSROOTsystem32cmd.exe
Davationesdrel.5.0 11binjava MyThread
Hello Fron Hyi hreadf

DEdavalloneiret.5.0.11bin)

nig. 10.10 Outpat of the Java Multithreaded application


Invoking the static method yield) voluntarily give up the execution of the thread and the thread is
moved to the pool of threads waiting to get their turn for execution, i.e. the thread enters the Ready'
state
E.g. MyThread. yield()
The static method sleep)
forces the thread to sleep for the duration mentioned the call, by sleep i.e.
the thread enters the
"Suspend' mode. Once the sleep period is the thread is moved to the pool
expired,
of threads
waiting to get their turn for execution, i.e. the thread enters the 'Ready' state. The method
sleep() only guarantees that the thread will sleep for the minimum period mentioned by the
the call. It will not argument to
on the scheduler.
guarantee anything on the resume of the thread after the sleep period. It is dependent
E.g. MyThread.sleep (100); Sleep for 100 milliseconds.
Calling a thread Object's wait() method causes the thread
object to wait. The thread will remain in the
Wait' state until another thread invokes the
notify) notifyAll) method of the thread object which is
or
waiting. The thread enters the 'Blocked' state when waiting for
input from I/O devices or waiting for
object lock
of accessing shared resources. The thread is moved to the 'Ready' state on receiving
in case
the IO input or on
acquiring the object lock. The thread enters the "Finished/Dead' state on
of the task assigned to it or when the completion
stop() method is explicitly invoked. The thread may also enter this
state if it is terminated
by an unrecoverable error condition.
For more information on Java threads, visit Sun Micro System's tutorial on Threads, available at
http:/java.sun.com/tutorial/applet/overview/threads.html
Summary So far we discussed about the various thread classes available for
ment of threads in creation and manage
a multithreaded system in a General Purpose
an RTOS perspective, Operating
POSIX threads and Win32 threads are the most System's perspective. From
libraries for thread creation and management. Many commonly used thread class
non-standard, proprietary thread classes are also
used by some proprietary RTOS. Portable threads (Pth), a
very portable POSIX/ANSI-C based library
from GNU, may be the "next generation threads
library. Pth provides
scheduling for multiple threads inside event driven applications. Visit non-preemptive priority based
for more details on GNU Portable threads http://www.gnu.org/software/pth
10.3.2.3 Thread Pre-emption Thread pre-emption is the act
thread (stopping the currently running hread temporarily). Threadof pre-empting the currently running.
dent on the Operating System. Thread pre-emption is pre-emnption ability is solely depen-
the threads. The execution switching among threads
performed sharing the CPU time among all
for
are known as *7Thread context switching. Thread
context switching is dependent on the tperating system s scheduler and
we say Thread', it falls into any one of the following types the type of the thread. When
Real-Time Operating System (RTOs) based Embedded 401
System Design
Level
User Level Threadser level threads do not have kernel/Operating System support and they id
solely in running proces, Even if a process contains multiple
the
e thread and will not switch the execution among the differentuser level threads, the OS treats it as
threads of it, It is the responsibilily
e orocess to schedule each thread as and when required, In
summary, user level threads of a process
e non-preemptive at thread level from OS perspective.

tarnel/System Level Thread Kermel level threads are individual units of execution, which the
Ke
a s separate threads. The OS interrupts the execution
OS
of the currently running kernel thread
hes the execution to another kernel thread based on the scheduling policies implemented byand
the
OS. In summary kerme level threads are pre-emptive.
ar user level threads, the execution switching (thread context
For
switching) happens only
whencalls
rrently executing user tevel thread is voluntarily blocked. Hence, no OS intervention and system the
curre

are involved in the context switching of user level threads. This makes context switching of user level
threads very fast. On the other hand, kernel level threads involve lots of kernel overhead and involve
sstem calls for context switching. However, kernel threads maintain a clear layer of abstraction and
allow threads to use system calls independently. There are many ways for binding user level threads
with system kermel levelthreads. The following section gives an overview ofvarious thread binding
models,
Many-to-One Model Here many user level threads are mapped to a single kernel thread. In this
model. the kernel treats all user level threads as singlethread and the execution switching among the
user level threads happens whena currentlyexecutinguserlevelthread voluntarilyblocksitself orrelin-
quishes the CPU Solaris Green threadsand GNU Portable Threads are examplesfor this. The PThread
example given under the POSIX thread library section is anillustrative example for application with
Many-to-One thread model.

One-to-One Model In One-to-One model,eachuser level thread isbondedto a kermel/system leyel


thread. Windows XP/NT/2000 and Linux threads are examples for One-to-One thread models. The
modified PThread' example given under the 'Thread Pre-emption' section is an illustrative example for
application with One-to-Onethread model.
Many-to-Many Model In this model many user level threads are allowed to be mapped to many
kernel threads. Windows NT/2000 with ThreadFibre package is an example for this.
10.3.2.4 Thread v/s Process I hope, by now you got a reasonably good knowledge ofprocess and
threads. Now let us summarise the properties of process and threads.

Thread Process
Thread is a single unit of execution and is part of process.Process is a program in execution and contains one or
more threads.
A thread does not have its own data memory and heapProcess has its own code memory, data memory and stack
memory. It shares the data memory and heap memory with memory.
other threads of the same process.
A thread cannot live independently; it lives within the A process contains at least one thread.
process.
There can be muliple threads ina process. The first thread Threads within a proces share the code, data and heap
unain thread) calls the main function and occupies the memory. Each thread holds.separate memory area for
start of the stack
memory of the process. stack (shares the total stack memory of the process).
402 Introduction to Embedded Systems

to create. Involves many Os


Processes are very expensive
Threads are very inexpensive to create
overhead.
and involves lot of Os
Context switching is complex
Context switching is inexpensive and fast comparatively
slower.
Overhead and is
allocated to it are reclaimed
the r e s o u r c e s
If a process dies,
f a thread expires, its stack is reclaimed by the process. and all the
associated threads of the process
by the OS
also dies.

You might also like