Realtime Embedded Multithreading Using Threadx And Mips Edward L Lamie Auth

afframecem72 7 views 78 slides May 20, 2025
Slide 1
Slide 1 of 78
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78

About This Presentation

Realtime Embedded Multithreading Using Threadx And Mips Edward L Lamie Auth
Realtime Embedded Multithreading Using Threadx And Mips Edward L Lamie Auth
Realtime Embedded Multithreading Using Threadx And Mips Edward L Lamie Auth


Slide Content

Realtime Embedded Multithreading Using Threadx
And Mips Edward L Lamie Auth download
https://ebookbell.com/product/realtime-embedded-multithreading-
using-threadx-and-mips-edward-l-lamie-auth-4342104
Explore and download more ebooks at ebookbell.com

Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Realtime Embedded Multithreading Using Threadx And Arm Edward L Lamie
https://ebookbell.com/product/realtime-embedded-multithreading-using-
threadx-and-arm-edward-l-lamie-1374584
Realtime Embedded Multithreading Using Thread X 2nd Edition Edward L
Lamie Auth
https://ebookbell.com/product/realtime-embedded-multithreading-using-
thread-x-2nd-edition-edward-l-lamie-auth-4562526
Realtime Embedded Components And Systems With Linux And Rtos 2nd
Edition Sam Siewert
https://ebookbell.com/product/realtime-embedded-components-and-
systems-with-linux-and-rtos-2nd-edition-sam-siewert-50246406
Realtime Embedded Systems Optimization Synthesis And Networking
Meikang Qiu And Jiayin Li
https://ebookbell.com/product/realtime-embedded-systems-optimization-
synthesis-and-networking-meikang-qiu-and-jiayin-li-2515800

Realtime Embedded Systems Opensource Operating Systems Perspective
Ivan Cibrario Bertolotti Gabriele Manduchi
https://ebookbell.com/product/realtime-embedded-systems-opensource-
operating-systems-perspective-ivan-cibrario-bertolotti-gabriele-
manduchi-4732214
Realtime Embedded Components And Systems 1st Edition Sam Siewert
https://ebookbell.com/product/realtime-embedded-components-and-
systems-1st-edition-sam-siewert-4739618
Realtime Embedded Systems Design Principles And Engineering Practices
1st Edition Xiaocong Fan
https://ebookbell.com/product/realtime-embedded-systems-design-
principles-and-engineering-practices-1st-edition-xiaocong-fan-5138752
Realtime Embedded Systems Christos Koulamas And Mihai T Lazarescu
https://ebookbell.com/product/realtime-embedded-systems-christos-
koulamas-and-mihai-t-lazarescu-54699168
Realtime Embedded Systems 1st Edition Jiacun Wang
https://ebookbell.com/product/realtime-embedded-systems-1st-edition-
jiacun-wang-7440452

Newnes is an imprint of Elsevier
30 Corporate Drive, Suite 400, Burlington, MA 01803, USA
Linacre House, Jordan Hill, Oxford OX2 8DP, UK
Copyright © 2009, Elsevier Inc. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in
any form or by any means, electronic, mechanical, photocopying, recording, or otherwise,
without the prior written permission of the publisher.
Permissions may be sought directly from Elsevier’s Science & Technology Rights
Department in Oxford, UK: phone: (44) 1865 843830, fax: (44) 1865 853333,
E-mail: [email protected]. You may also complete your request
online via the Elsevier homepage (http://elsevier.com), by selecting “Support & Contact”
then “Copyright and Permission” and then “Obtaining Permissions.”
Library of Congress Cataloging-in-Publication Data
Application submitted
British Library Cataloguing-in-Publication Data
A catalogue record for this book is available from the British Library.
ISBN: 978-1-85617-631-6
For information on all Newnes publications
visit our Web site at www.elsevierdirect.com
Typeset by Charon Tec Ltd., A Macmillan Company. (www.macmillansolutions.com)
08 09 10 10 9 8 7 6 5 4 3 2 1
Printed in the United States of America

à mes anc ê tres qu é becois

www.newnespress.com
Preface
Embedded systems are ubiquitous. These systems are found in most consumer
electronics, automotive, government, military, communications, and medical equipment.
Most individuals in developed countries have many such systems and use them daily,
but relatively few people realize that these systems actually contain embedded computer
systems. Although the fi eld of embedded systems is young, the use and importance of
these systems is increasing, and the fi eld is rapidly growing and maturing.
This book is intended for persons who develop embedded systems, or for those who
would like to know more about the process of developing such systems. Although
embedded systems developers are typically software engineers or electrical engineers,
many people from other disciplines have made signifi cant contributions to this fi eld.
This book is specifi cally targeted toward embedded applications that must be small, fast,
reliable, and deterministic.
1
This book is composed of 14 chapters that cover embedded and real-time concepts, the
MIPS
®
processor, all the services provided by the ThreadX
®
real-time operating system
(RTOS), solutions to classical problem areas, and a case study. I assume the reader has
a programming background in C or C , so we won’t devote any time to programming
fundamentals. Depending on the background of the reader, the chapters of the book may
be read independently.
There are several excellent books written about embedded systems. However, most of these
books are written from a generalist point of view. This book is unique because it is based
on embedded systems development using a typical commercial RTOS, as well as a typical
microprocessor. This approach has the advantage of providing specifi c knowledge and
techniques, rather than generic concepts that must be converted to your specifi c system.
Thus, you can immediately apply the topics in this book to your development efforts.
Because an actual RTOS is used as the primary tool for embedded application
development, there is no discussion about the merits of building your own RTOS or
1
Such systems are sometimes called deeply embedded systems.

xvi Preface
forgoing an RTOS altogether. I believe that the relatively modest cost of a commercial
RTOS provides a number of signifi cant advantages over attempts to “ build your own. ” For
example, most commercial RTOS companies have spent years refi ning and optimizing
their systems. Their expertise and product support may play an important role in the
successful development of your system.
The RTOS chosen for use in this book is ThreadX
2
(version 5). This RTOS was selected
for a variety of reasons, including reliability, ease of use, low cost, widespread use, and
the maturity of the product due to the extensive experience of its developers. This RTOS
contains most of the features found in contemporary RTOSes, as well as several advanced
features that are not. Another notable feature of this RTOS is the consistent and readable
coding convention used within its application programming interface (API). Developing
applications is highly intuitive because of the logical approach of the API.
Although I chose the C programming language for this book, you could use C instead
for any of the applications described in this book.
There is a CD included with this book that contains a limited ThreadX
3
system. You may
use this system to perform your own experiments, run the included demonstration system,
and experiment with the projects described throughout the book.
Typographical conventions are used throughout this book so that key concepts are
communicated easily and unambiguously. For example, keywords such as main or int are
displayed in a distinctive typeface, whether these keywords are in a program or appear
in the discussion about a program. This typeface is also used for all program segment
listings or when actual input or output is illustrated. When an identifi er name such as
MyVar is used in the narrative portion of the book, it will appear in italics. The italics
typeface will also be used when new topics are introduced or to provide emphasis.
www.newnespress.com
2
ThreadX is a registered trademark of Express Logic, Inc. The ThreadX API, associated data
structures, and data types are copyrights of Express Logic, Inc. MIPS is a registered trademark of
MIPS Processors, Inc.
3
Express Logic, Inc. has granted permission to use this demonstration system for the sample
systems and the case study in this book.

www.newnespress.com
Embedded and Real-time Systems
CHAPTER 1
1.1 Introduction
Although the history of embedded systems is relatively short,
1
the advances and
successes of this fi eld have been profound. Embedded systems are found in a vast array of
applications such as consumer electronics, “ smart ” devices, communication equipment,
automobiles, desktop computers, and medical equipment.
2
1.2 What is an Embedded System?
In recent years, the line between embedded and nonembedded systems has blurred, largely
because embedded systems have expanded to a vast array of applications. However, for
practical purposes, an embedded system is defi ned here as one dedicated to a specifi c purpose
and consisting of a compact, fast, and extremely reliable operating system that controls the
microprocessor located inside a device. Included in the embedded system is a collection of
programs that run under that operating system, and of course, the microprocessor.
3
1
The fi rst embedded system was developed in 1971 by the Intel Corporation, which produced the
4004 microprocessor chip for a variety of business calculators. The same chip was used for all the
calculators, but software in ROM provided unique functionality for each calculator. Source: The
Intel 4004 website at
2
Approximately 98% of all microprocessors are used in embedded systems. Turley, Jim, The Two
Percent Solution , Embedded Systems Programming, Vol. 16, No. 1, January 2003.
3
The microprocessor is often called a microcontroller, embedded microcontroller, network
processor, or digital signal processor ; it consists of a CPU, RAM, ROM, I/O ports, and timers.

2 Chapter 1
Because an embedded system is part of a larger system or device, it is typically housed on
a single microprocessor board and the associated programs are stored in ROM.
4
Because
most embedded systems must respond to inputs within a small period of time, these
systems are frequently classifi ed as real-time systems. For simple applications, it might
be possible for a single program (without an RTOS) to control an embedded system, but
typically an RTOS or kernel is used as the engine to control the embedded system.
1.3 Characteristics of Embedded Systems
Another important feature of embedded systems is determinism . There are several aspects
to this concept, but each is built on the assumption that for each possible state and each
set of inputs, a unique set of outputs and next state of the system can be, in principle,
predicted. This kind of determinism is not unique to embedded systems; it is the basis
for virtually all kinds of computing systems. When you say that an embedded system
is deterministic, you are usually referring totemporal determinism . A system exhibits
temporal determinism if the time required to process any task is fi nite and predictable. In
particular, we are less concerned with average response time than we are with worst-case
response time. In the latter case, we must have a guarantee on the upper time limit, which
is an example of temporal determinism.
An embedded system is typically encapsulated by the hardware it controls, so end-users
are usually unaware of its presence. Thus, an embedded system is actually a computer
system that does not have the outward appearances of a computer system. An embedded
system typically interacts with the external world, but it usually has a primitive or
nonexistent user interface.
The embedded systems fi eld is a hybrid that draws extensively from disciplines such as
software engineering, operating systems, and electrical engineering. Embedded systems
has borrowed liberally from other disciplines and has adapted, refi ned, and enhanced
those concepts and techniques for use in this relatively young fi eld.
1.4 Real-time Systems
As noted above, an embedded system typically must operate within specifi ed time
constraints. When such constraints exist, we call the embedded system a real-time system .
www.newnespress.com
4
We often say that embedded systems are ROMable or scalable .

Embedded and Real-time Systems 3
www.newnespress.com
This means that the system must respond to inputs or events within prescribed time
limits, and the system as a whole must operate within specifi ed time constraints. Thus, a
real-time system must not only produce correct results, but also it must produce them in a
timely fashion. The timing of the results is sometimes as important as their correctness.
There are two important subclasses of real-time constraints: hard real-time and soft real-
time. Hard real-time refers to highly critical time constraints in which missing even one
time deadline is unacceptable, possibly because it would result in catastrophic system
failure. Examples of hard real-time systems include air traffi c control systems, medical
monitoring systems, and missile guidance systems. Soft real-time refers to situations in
which meeting the time constraints is desirable, but not critical to the operation of the
system.
1.5 Real-time Operating Systems and Real-time Kernels
Relatively few embedded applications can be developed effectively as a single control
program, so we consider only commercially available real-time operating systems
(RTOSes) and real-time kernels here. A real-time kernel is generally much smaller than
a complete RTOS. In contemporary operating system terminology, a kernel is the part of
the operating system that is loaded into memory fi rst and remains in memory while the
application is active. Likewise, a real-time kernel is memory-resident and provides all the
necessary services for the embedded application. Because it is memory-resident, a real-
time kernel must be as small as possible.
kernel and other RTOS services.
Other RTOS services
Kernel
Figure 1.1: RTOS kernel

4 Chapter 1
The operation of an embedded system entails the execution of processes, and tasks or
threads, either in response to external or internal inputs, or in the normal processing
required for that system. The processing of these entities must produce correct results
within specifi ed time constraints.
1.6 Processes, Tasks, and Threads
The term process is an operating system concept that refers to an independent executable
program that has its own memory space. The terms “ process ” and “ program ” are often
used synonymously, but technically a process is more than a program: it includes the
execution environment for the program and handles program bookkeeping details for the
operating system. A process can be launched as a separately loadable program, or it can
be a memory-resident program that is launched by another process. Operating systems
are often capable of running many processes concurrently. Typically, when an operating
system executes a program, it creates a new process for it and maintains within that
process all the bookkeeping information needed. This implies that there is a one-to-one
relationship between the program and the process, i.e., one program, one process.
When a program is divided into several segments that can execute concurrently, we refer
to these segments as threads. A thread is a semi-independent program segment; threads
share the same memory space within a program. The terms “ task ” and “ thread ” are
frequently used interchangeably. However, we will use the term “ thread ” in this book
because it is more descriptive and more accurately refl ects the processing that occurs.

www.newnespress.com
Process Thread 1 Thread 2 Thread n• • •
ProgramProgram
Figure 1.2: Comparison of processes and threads

Embedded and Real-time Systems 5
www.newnespress.com
1.7 Architecture of Real-time Systems
The architecture of a real-time system determines how and when threads are processed.
Two common architectures are the control loop with polling
5
approach and the
preemptive scheduling model. In the control loop with polling approach, the kernel
executes an infi nite loop, which polls the threads in a predetermined pattern. If a thread
needs service, then it is processed. There are several variants to this approach, including
time-slicing
6
to ensure that each thread is guaranteed access to the processor.
contains an illustration of the control loop with polling approach.
Although the control loop with polling approach is relatively easy to implement, it has
several serious limitations. For example, it wastes much time because the processor polls
threads that do not need servicing, and a thread that needs attention has to wait its turn
until the processor fi nishes polling other threads. Furthermore, this approach makes no
Thread n Thread 1
Thread 2Thread 4
Thread 3
The kernel polls each thread
in sequence to determine
whether or not it needs
the process
Figure 1.3: Control loop with polling approach
5
The control loop with polling approach is sometimes called the super loop approach.
6
Each thread is allocated a predetermined slice of time in which to execute.

6 Chapter 1
distinction between the relative importance of the threads, so it is diffi cult to give threads
with critical requirements fast access to the processor.
Another approach that real-time kernels frequently use is preemptive scheduling . In this
approach, threads are assigned priorities and the kernel schedules processor access for
the thread with the highest priority. There are several variants to this approach including
techniques to ensure that threads with lower priorities get some access to the processor.

thread is assigned a priority from zero (0) to some upper limit.
7
Assume that priority zero
is the highest priority.
An essential feature in preemptive scheduling schemes is the ability to suspend the
processing of a thread when a thread that has a higher priority is ready for processing.
The process of saving the current information of the suspended thread so that another
thread can execute is called context switching . This process must be fast and reliable
www.newnespress.com
Thread n
PR 3
Thread 1
PR 5
Thread 2
PR 10
Thread 4
PR 5
Thread 3
PR 0
The kernel schedules the
thread with the highest priority
(in this case, thread
3 with priority 0) for processor
access
Figure 1.4: Preemptive scheduling method
7
ThreadX provides 1024 distinct priority values, where 0 represents the highest priority.

Embedded and Real-time Systems 7
www.newnespress.com
because the suspended thread must be able to resume execution exactly at the point where
it was suspended when it ultimately regains control of the processor.
Embedded systems need to respond to inputs or events accurately and within specifi ed
deadlines. This is accomplished in part by means of an interrupt , which is a signal to the
processor that an event has occurred and that immediate attention may be required. An
interrupt is handled with aninterrupt service routine (ISR) , which may activate a thread
with a higher priority than the currently executing thread. In this case, the ISR would
suspend the currently executing thread and permit the higher priority thread to proceed.
Interrupts can be generated from software
8
or by a variety of hardware devices.
1.8 Embedded Systems Development
Embedded applications should be designed and developed using sound software
engineering principles. Because most embedded applications are real-time systems,
one major difference from traditional computer applications is the requirement to
adhere strictly to prescribed time constraints.
9
The requirements and design phases are
performed with the same rigor as any other software application.
Another major consideration in embedded systems development is that the modules (that
is, the threads) are not designed to be executed in a procedural manner, as is the case with
traditional software systems. The threads of an embedded application are designed to
be executed independently of each other or in parallel
10
so this type of system is called
multithreaded .
11
Because of this apparent parallelism, the traditional software-control
structures are not always applicable to embedded systems.
A real-time kernel is used as the engine to drive the embedded application, and the
software design consists of threads to perform specifi c operations, using inter-thread
communication facilities provided by the kernel. Although most embedded systems
development is done in the C (or C ) programming language, some highly critical
portions of the application are often developed in assembly language.
8
Software interrupts are also called traps or exceptions .
9
Some writers liken the study of real-time systems to the science of performance guarantees .
10
In cases where there is only one processor, threads are executed in pseudo-parallel.
11
Multithreading is sometimes called multitasking .

8 Chapter 1
1.9 Key Terms and Phrases
www.newnespress.com
control loop with polling priority
determinism real-time kernel
embedded system real-time system
interrupt ROMable
microprocessor RTOS
multithreading scalable
preemptive scheduling Thread

First Look at a System Using
an RTOS
CHAPTER 2
2.1 Operating Environment
We will use the Win32 version of ThreadX because it permits developers to develop
prototypes of their applications in the easy-to-use and prevalent Windows programming
environment. We achieve complete ThreadX simulation by using Win32 calls. The
ThreadX-specifi c application code developed in this environment will execute in an
identical fashion on the eventual target hardware. Thus, ThreadX simulation allows real
software development to start well before the actual target hardware is available. We will
use Microsoft Visual C/C Tools to compile all the embedded systems in this book.
2.2 Installation of the ThreadX Demonstration System
There is a demonstration version of ThreadX on the CD included with this book. View
the Readme fi le for information about installing and using this demonstration system.
2.3 Sample System with Two Threads
The fi rst step in mastering the use of ThreadX is to understand the nature and behavior
of threads. We will achieve this purpose by performing the following operations in this
sample system: create several threads, assign several activities to each thread, and compel
the threads to cooperate in the execution of their activities. A mutex will be used to
coordinate the thread activities, and a memory byte pool will be used to create stacks for
the threads. (Mutexes and stacks are described in more detail later.)
www.newnespress.com

10 Chapter 2
The fi rst two components that we create are two threads named Speedy_Thread and
Slow_Thread. Speedy_Thread will have a higher priority than Slow_Thread and will
generally fi nish its activities more quickly. ThreadX uses a preemptive scheduling
algorithm, which means that threads with higher priorities generally have the ability to
preempt the execution of threads with lower priorities. This feature may help Speedy_
Thread to complete its activities more quickly than Slow_Thread. Figure 2.1
illustration of the components that we will use in the sample system.
In order to create the threads, you need to assign each of them a stack : a place where
the thread can store information, such as return addresses and local variables, when it is
preempted. Each stack requires a block of contiguous bytes. You will allocate these bytes
from a memory byte pool, which you will also create. The memory byte pool could also
be used for other ThreadX objects, but we will restrict its usage to the two threads in this
system. There are other methods by which we could assign memory space for a stack,
including use of an array and a memory block pool (to be discussed later). We choose to
use the memory byte pool in this sample system only because of its inherent simplicity.
We will use a ThreadX object called a mutex in this sample system to illustrate the
concept of mutual exclusion. Each of the two threads has two sections of code known as
critical sections . Very generally, a critical section is one that imposes certain constraints
on thread execution. In the context of this example, the constraint is that when a thread
is executing a critical section, it must not be preempted by any other thread executing a
critical section — no two threads can be in their respective critical sections at the same
www.newnespress.com
Speedy_Thread
my_byte_pool
my_mutex
Slow_Thread
Figure 2.1: Components of the sample system

First Look at a System Using an RTOS 1 1
time. A critical section typically contains shared resources,
1
so there is the potential for
system failure or unpredictable behavior when more than one thread is in a critical section.
A mutex is an object that acts like a token or gatekeeper. To gain access to a critical
section, a thread must acquire “ ownership ” of the mutex, and only one thread can own
a given mutex at the same time. We will use this property to provide inter-thread mutual
exclusion protection. For example, if Slow_Thread owns the mutex, then Speedy_Thread
must wait to enter a critical section until Slow_Thread gives up ownership of the mutex,
even though Speedy_Thread has a higher priority. Once a thread acquires ownership of a
mutex, it will retain ownership until it voluntarily gives up that mutex. In other words, no
thread can preempt a mutex owned by another thread regardless of either thread’s priority.
This is an important feature that provides inter-thread mutual exclusion.
Each of the two threads in the sample system has four activities that will be executed
repeatedly.
Activities 2 and 4 appear in shaded boxes that represent critical sections for that thread.
Similarly,
that Speedy_Thread has a priority of 5, which is higher than the priority of 15 that is
assigned to the Slow_Thread.
Activity 1
Sleep 2 ticks
Activity 3
Sleep 4 ticks
Activity 2
Get and keep mutex
for 5 ticks
Activity 4
Get and keep mutex
for 3 ticks
Figure 2.2: Activities of the Speedy_Thread (priority 5)
Activity 6
Sleep 8 ticks
Activity 8
Sleep 9 ticks
Activity 5
Get and keep mutex
for 12 ticks
Activity 7
Get and keep mutex
for 11 ticks
Figure 2.3: Activities of the Slow_Thread (priority 15)
1
Or, it contains code that accesses shared resources.
www.newnespress.com

12 Chapter 2
2.4 Creating the ThreadX Objects
Program listing 02_sample_system.c is located at the end of this chapter and on the
attached CD. It contains the complete source code for our sample system. Detailed
discussion of the specifi cs of this listing is included in later chapters to provide a
highlight of the essential portions of the system.
main features of the source code listing.
The
main() portion of the basic structure contains exactly one executable statement, as
follows:
tx_kernel_enter();
The above entry function turns over control to ThreadX (and does not return!). ThreadX
performs initialization of various internal data structures and then processes the
application defi nitions and the thread entry defi nitions. ThreadX then begins scheduling
and executing application threads. The purpose of the
tx_application_defi ne function in our
sample system is to defi ne all the ThreadX components that will be used. For example,
we need to defi ne a memory byte pool, two threads, and one mutex. We also need to
allocate memory from the byte pool for use as thread stacks. The purpose of the thread
entry functions section is to prescribe the behavior of the two threads in the system.
We will consider only one of the thread entry functions in this discussion because both
entry functions are similar.
Speedy_Thread.
Recall that activities 2 and 4 are the critical sections of Speedy_Thread. Speedy_Thread
seeks to obtain ownership of the mutex with the following statement:
tx_mutex_get( & my_mutex, TX_WAIT_FOREVER);
www.newnespress.com
Comments, #include directives,
declarations, definitions, prototypes
main()
tx_application_define function
Thread entry functions
Figure 2.4: Basic structure of sample system

First Look at a System Using an RTOS 1 3
If Slow_Thread already owns the mutex, then Speedy_Thread will “ wait forever ” for its
turn to obtain ownership. When Speedy_Thread completes a critical section, it gives up
ownership of the mutex with the following statement:
tx_mutex_put( & my_mutex);
When this statement is executed, Speedy_Thread relinquishes ownership of the mutex, so
it is once again available. If Slow_Thread is waiting for the mutex, it will then have the
opportunity to acquire it.
/* Entry function definition of the "Speedy_Thread"
which has a higher priority than the “Slow_Thread” */
void Speedy_Thread_entry(ULONG thread_input)
{
UINT status;
ULONG current_time;
While (1)
{
/* Activity 1: 2 timer-ticks */
tx_thread_sleep(2);
/* Get the mutex with suspension */
tx_mutex_get(&my_mutex, TX_WAIT_FOREVER);
/* Activity 2: 5 timer-ticks */ *** critical section *** */
tx_thread_sleep(5);
/* Release the mutex */
tx_mutex_put(&my_mutex);
/* Activity 3: 4 timer-ticks */
tx_thread_sleep(4);
/* Get the mutex with suspension */
tx_mutex_get(&my_mutex, TX_WAIT_FOREVER);
/* Activity 4: 3 timer-ticks *** critical section *** */
tx_thread_sleep(3);
/* Release the mutex */
tx_mutex_put(&my_mutex);
current_time = tx_time_get();
printf("Current Time: %5lu Speedy_Thread finished cycle...",
current_time);
}
}
Figure 2.5: Entry function defi nition for the Speedy_Thread
www.newnespress.com

14 Chapter 2
www.newnespress.com
The entry function for Speedy_Thread concludes by getting the current system time and
displaying that time along with a message that Speedy_Thread has fi nished its current
cycle of activities.
2.5 Compiling and Executing the Sample System
Compile and execute the sample system contained in 02_sample_system.c that is located
on the attached CD. A complete listing appears in a section at the end of this chapter.
2.6 Analysis of the System and the Resulting Output

be similar, but not necessarily identical.
The minimum amount of time in which Speedy_Thread can complete its cycle of
activities is 14 timer-ticks. By contrast, the Slow_Thread requires at least 40 timer-ticks
to complete one cycle of its activities. However, the critical sections of the Slow_Thread
will cause delays for the Speedy_Thread. Consider the sample output in
the Speedy_Thread fi nishes its fi rst cycle at time 34, meaning that it encountered a delay
of 20 timer-ticks because of the Slow_Thread. The Speedy_Thread completes subsequent
cycles in a more timely fashion but it will always spend a lot of time waiting for the
Slow_Thread to complete its critical section.
2.7 Listing of 02_sample_system.c
The sample system named 02_sample_system.c is located on the attached CD. The
complete listing appears below; line numbers have been added for easy reference.
Current Time: 34 Speedy_Thread finished cycle...
Current Time: 40 Slow_Thread finished cycle...
Current Time: 56 Speedy_Thread finished cycle...
Current Time: 77 Speedy_Thread finished cycle...
Current Time: 83 Slow_Thread finished cycle...
Current Time: 99 Speedy_Thread finished cycle...
Current Time: 120 Speedy_Thread finished cycle...
Current Time: 126 Slow_Thread finished cycle...
Current Time: 142 Speedy_Thread finished cycle...
Current Time: 163 Speedy
_Thread finished cycle...
Figure 2.6: Output produced by sample system

First Look at a System Using an RTOS 1 5
www.newnespress.com
001 /* 02_sample_system.c
002
003 Create two threads, one byte pool, and one mutex.
004 The threads cooperate with each other via the mutex. */
005
006
007 /****************************************************/
008 /* Declarations, Defi nitions, and Prototypes */
009 /****************************************************/
010
011 #include “tx_api.h”
012 #include stdio.h
013
014 #defi ne DEMO_STACK_SIZE 1024
015 #defi ne DEMO_BYTE_POOL_SIZE 9120
016
017
018 /* Defi ne the ThreadX object control blocks … */
019

020 TX_THREAD Speedy_Thread;
021 TX_THREAD Slow_Thread;
022
023 TX_MUTEX my_mutex;
024
025 TX_BYTE_POOL my_byte_pool;
026
027
028 /* Defi ne thread prototypes. */
029
030 void Speedy_Thread_entry(ULONG thread_input);
031 void Slow_Thread_entry(ULONG thread_input);
032
033
034 /****************************************************/
035 /* Main Entry Point */
036 /****************************************************/
037
038 /* Defi ne main entry point. */
039
040 int main()
041 {

16 Chapter 2
042
043 /* Enter the ThreadX kernel. */
044 tx_kernel_enter();
045 }
046
047
048
049 /****************************************************/
050 /* Application Defi nitions */
051 /****************************************************/
052
053
054 /* Defi ne what the initial system looks like. */
055
056 void tx_application_defi ne(void *fi rst_unused_memory)
057 {
058
059 CHAR *pool_pointer;
060
061
062
/* Create a byte memory pool from which to allocate
063 the thread stacks. */
064 tx_byte_pool_create( & my_byte_pool, “my_byte_pool”,
065 fi rst_unused_memory,
066 DEMO_BYTE_POOL_SIZE);
067
068 /* Put system defi nition stuff in here, e.g., thread
069 creates and other assorted create information. */
070
071 /* Allocate the stack for the Speedy_Thread. */
072 tx_byte_allocate( & my_byte_pool, (VOID **) & pool_pointer,
073 DEMO_STACK_SIZE, TX_NO_WAIT);
074
075 /* Create the Speedy_Thread. */
076 tx_thread_create( & Speedy_Thread, “Speedy_Thread”,
077 Speedy_Thread_entry, 0,
078 pool_pointer, DEMO_STACK_SIZE, 5, 5,
079 TX_NO_TIME_SLICE, TX_AUTO_START);
080

081 /* Allocate the stack for the Slow_Thread. */
www.newnespress.com

First Look at a System Using an RTOS 1 7
www.newnespress.com
082 tx_byte_allocate( & my_byte_pool, (VOID **) & pool_pointer,
083 DEMO_STACK_SIZE, TX_NO_WAIT);
084
085 /* Create the Slow_Thread. */
086 tx_thread_create( & Slow_Thread, “Slow_Thread”,
087 Slow_Thread_entry, 1, pool_pointer,
088 DEMO_STACK_SIZE, 15, 15,
089 TX_NO_TIME_SLICE, TX_AUTO_START);
090
091 /* Create the mutex used by both threads */
092 tx_mutex_create( & my_mutex, “my_mutex”, TX_NO_INHERIT);
093
094
095 }
096
097
098 /****************************************************/
099 /* Function Defi nitions */
100 /****************************************************/
101

102
103 /* Entry function defi nition of the “Speedy_Thread”
104 it has a higher priority than the “Slow_Thread” */
105
106 void Speedy_Thread_entry(ULONG thread_input)
107 {
108
109 ULONG current_time;
110
111 while (1)
112 {
113 /* Activity 1: 2 timer-ticks */
114 tx_thread_sleep(2);
115
116 /* Get the mutex with suspension */
117 tx_mutex_get( & my_mutex, TX_WAIT_FOREVER);
118
119 /* Activity 2: 5 timer-ticks *** critical section *** */
120 tx_thread_sleep(5);
121

18 Chapter 2
122 /* Release the mutex */
123 tx_mutex_put( & my_mutex);
124
125 /* Activity 3: 4 timer-ticks */
126 tx_thread_sleep(4);
127
128 /* Get the mutex with suspension */
129 tx_mutex_get( & my_mutex, TX_WAIT_FOREVER);
130
131 /* Activity 4: 3 timer-ticks *** critical section *** */
132 tx_thread_sleep(3);
133
134 /* Release the mutex */
135 tx_mutex_put( & my_mutex);
136
137 current_time tx_time_get();
138 printf(“ Current Time: %5lu Speedy_Thread fi nished a
cycle … ”,
139 current_time);

140
141 }
142 }
143
144 /****************************************************/
145
146 /* Entry function defi nition of the “Slow_Thread”
147 it has a lower priority than the “Speedy_Thread” */
148
149 void Slow_Thread_entry(ULONG thread_input)
150 {
151
152
153 ULONG current_time;
154
155 while(1)
156 {
157 /* Activity 5 - 12 timer-ticks *** critical section *** */
158
159 /* Get the mutex with suspension */

160 tx_mutex_get( & my_mutex, TX_WAIT_FOREVER);
161
www.newnespress.com

First Look at a System Using an RTOS 1 9
www.newnespress.com
162 tx_thread_sleep(12);
163
164 /* Release the mutex */
165 tx_mutex_put( & my_mutex);
166
167 /* Activity 6 - 8 timer-ticks */
168 tx_thread_sleep(8);
169
170 /* Activity 7 - 11 timer-ticks *** critical section *** */
171
172 /* Get the mutex with suspension */
173 tx_mutex_get( & my_mutex, TX_WAIT_FOREVER);
174
175 tx_thread_sleep(11);
176
177 /* Release the mutex */
178 tx_mutex_put( & my_mutex);
179
180 /* Activity 8 - 9 timer-ticks */
181 tx_thread_sleep(9);

182
183 current_time tx_time_get();
184 printf(“Current Time: %5lu Slow_Thread finished a cycle … ”,
185 current_time);
186
187 }
188 }
2.8 Key Terms and Phrases
application defi ne function preemption
critical section priority
current time scheduling threads
initialization sleep time
inter-thread mutual exclusion stack
kernel entry suspension
memory byte pool template
mutex thread
mutual exclusion thread entry function
ownership of mutex timer-tick

20 Chapter 2
2.9 Problems
1. Modify the sample system to compute the average cycle time for the Speedy Thread
and the Slow Thread. You will need to add several variables and perform several
computations in each of the two thread entry functions. You will also need to get the
current time at the beginning of each thread cycle.
2. Modify the sample system to bias it in favor of the Speedy Thread. For example,
ensure that Slow Thread will not enter a critical section if the Speedy Thread is
within two timer-ticks of entering its critical section. In that case, the Slow Thread
would sleep two more timer-ticks and then attempt to enter its critical section.
www.newnespress.com

www.newnespress.com
RTOS Concepts and Defi nitions
CHAPTER 3
3.1 Introduction
The purpose of this chapter is to review some of the essential concepts and defi nitions
used in embedded systems. You have already encountered several of these terms in
previous chapters, and you will read about several new concepts here.
3.2 Priorities
Most embedded real-time systems use a priority system as a means of establishing the
relative importance of threads in the system. There are two classes of priorities: static and
dynamic. A static priority is one that is assigned when a thread is created and remains
constant throughout execution. A dynamic priority is one that is assigned when a thread
is created, but can be changed at any time during execution. Furthermore, there is no limit
on the number of priority changes that can occur.
ThreadX provides a fl exible method of dynamic priority assignment. Although each
thread must have a priority, ThreadX places no restrictions on how priorities may be
used. As an extreme case, all threads could be assigned the same priority that would
never change. However, in most cases, priority values are carefully assigned and modifi ed
only to refl ect the change of importance in the processing of threads. As illustrated by

represents the highest priority and the value 31 represents the lowest priority.
1
1
The default priority range for ThreadX is 0 through 31, but up to 1024 priority levels can be used.

22 Chapter 3
3.3 Ready Threads and Suspended Threads
ThreadX maintains several internal data structures to manage threads in their various
states of execution. Among these data structures are the Suspended Thread List and the
Ready Thread List. As implied by the nomenclature, threads on the Suspended Thread
List have been suspended — temporarily stopped executing — for some reason. Threads on
the Ready Thread List are not currently executing but are ready to run.
When a thread is placed in the Suspended Thread List, it is because of some event or
circumstance, such as being forced to wait for an unavailable resource. Such a thread
remains in that list until that event or circumstance has been resolved. When a thread is
removed from the Suspended Thread List, one of two possible actions occurs: it is placed
on the Ready Thread List, or it is terminated.
When a thread is ready for execution, it is placed on the Ready Thread List. When
ThreadX schedules a thread for execution, it selects and removes the thread in that list
that has the highest priority. If all the threads on the list have equal priority, ThreadX
selects the thread that has been waiting the longest.
2

how the Ready Thread List appears.
If for any reason a thread is not ready for execution, it is placed in the Suspended Thread
List. For example, if a thread is waiting for a resource, if it is in “ sleep ” mode, if it was
www.newnespress.com
Priority
value
Meaning
0
Highest
priority
1
31
:
Lowest
priority
Figure 3.1: Priority values
2
This latter selection algorithm is commonly known as First In First Out, or FIFO.

RTOS Concepts and Defi nitions 23
www.newnespress.com
created with a TX_DONT_START option, or if it was explicitly suspended, then it will
reside in the Suspended Thread List until that situation has cleared.
depiction of this list.
3.4 Preemptive, Priority-Based Scheduling
The term preemptive, priority-based scheduling refers to the type of scheduling in which
a higher priority thread can interrupt and suspend a currently executing thread that has a
lower priority.
In this example, Thread 1 has control of the processor. However, Thread 2 has a higher
priority and becomes ready for execution. ThreadX then interrupts Thread 1 and gives
Thread 2 control of the processor. When Thread 2 completes its work, ThreadX returns
control to Thread 1 at the point where it was interrupted. The developer does not have to
be concerned about the details of the scheduling process. Thus, the developer is able to
develop the threads in isolation from one another because the scheduler determines when
to execute (or interrupt) each thread.
• • •
Threads ready to be executed are ordered by
priority, then by FIFO
Figure 3.2: Ready Thread List
• • •
Threads are not sorted in any particular order
Figure 3.3: Suspended Thread List

24 Chapter 3
3.5 Round-Robin Scheduling
The term round-robin scheduling refers to a scheduling algorithm designed to provide
processor sharing in the case in which multiple threads have the same priority. There are
two primary ways to achieve this purpose, both of which are supported by ThreadX.
Figure 3.5 rst method of round-robin scheduling, in which Thread 1 is
executed for a specifi ed period of time, then Thread 2, then Thread 3, and so on to Thread
n , after which the process repeats. See the section titled Time-Slice for more information
about this method. The second method of round-robin scheduling is achieved by the use
of a cooperative call made by the currently executing thread that temporarily relinquishes
control of the processor, thus permitting the execution of other threads of the same or
higher priority. This second method is sometimes called cooperative multithreading .

With cooperative multithreading, when an executing thread relinquishes control of the
processor, it is placed at the end of the Ready Thread List, as indicated by the shaded
thread in the fi gure. The thread at the front of the list is then executed, followed by the
next thread on the list, and so on until the shaded thread is at the front of the list. For
convenience,
Ready Thread List can hold threads with several different priorities. In that case, the
scheduler will restrict its attention to the threads that have the highest priority.
www.newnespress.com
Time
Priority
Thread 1
interrupted
Thread 1
begins
Thread 1
finishes
Thread 2
executing
Figure 3.4: Thread preemption

RTOS Concepts and Defi nitions 25
www.newnespress.com
In summary, the cooperative multithreading feature permits the currently executing thread
to voluntarily give up control of the processor. That thread is then placed on the Ready
Thread List and it will not gain access to the processor until after all other threads that
have the same (or higher) priority have been processed.
3.6 Determinism
As noted in Chapter 1, an important feature of real-time embedded systems is the concept
of determinism. The traditional defi nition of this term is based on the assumption that
for each system state and each set of inputs, a unique set of outputs and next state of the
system can be determined. However, we strengthen the defi nition of determinism for
real-time embedded systems by requiring that the time necessary to process any task be
predictable. In particular, we are less concerned with average response time than we are
with worst-case response time. For example, we must be able to guarantee the worst-case
Thread 4 Thread 3
Thread 2
Thread 1Thread n



Figure 3.5: Round-robin processing
• • •
Ready thread list containing threads with the same
priority currently executing thread (shaded) voluntarily relinquishes
the processor and is placed on this list.
Figure 3.6: Example of cooperative multithreading

26 Chapter 3
response time for each system call in order for a real-time embedded system to be
deterministic. In other words, simply obtaining the correct answer is not adequate. We
must get the right answer within a specifi ed time frame.
Many RTOS vendors claim their systems are deterministic and justify that assertion by
publishing tables of minimum, average, and maximum number of clock cycles required
for each system call. Thus, for a given application in a deterministic system, it is possible
to calculate the timing for a given number of threads, and determine whether real-time
performance is actually possible for that application.
3.7 Kernel
A kernel is a minimal implementation of an RTOS. It normally consists of at least a
scheduler and a context switch handler. Most modern commercial RTOSes are actually
kernels, rather than full-blown operating systems.
3.8 RTOS
An RTOS is an operating system that is dedicated to the control of hardware, and must
operate within specifi ed time constraints. Most RTOSes are used in embedded systems.
3.9 Context Switch
A context is the current execution state of a thread. Typically, it consists of such items
as the program counter, registers, and stack pointer. The term context switch refers to
the saving of one thread’s context and restoring a different thread’s context so that it can
be executed. This normally occurs as a result of preemption, interrupt handling, time-
slicing (see below), cooperative round-robin scheduling (see below), or suspension of
a thread because it needs an unavailable resource. When a thread’s context is restored,
then the thread resumes execution at the point where it was stopped. The kernel performs
the context switch operation. The actual code required to perform context switches is
necessarily processor-specifi c.
3.10 Time-Slice
The length of time (i.e., number of timer-ticks) for which a thread executes before
relinquishing the processor is called itstime-slice . When a thread’s (optional) time-slice
www.newnespress.com

RTOS Concepts and Defi nitions 27
www.newnespress.com
expires in ThreadX, all other threads of the same or higher priority levels are given a
chance to execute before the time-sliced thread executes again. Time-slicing provides
another form of round-robin scheduling. ThreadX provides optional time-slicing on a
per-thread basis. The thread’s time-slice is assigned during creation and can be modifi ed
during execution. If the time-slice is too short, then the scheduler will waste too much
processing time performing context switches. However, if the time-slice is too long, then
threads might not receive the attention they need.
3.11 Interrupt Handling
An essential requirement of real-time embedded applications is the ability to provide
fast responses to asynchronous events, such as hardware or software interrupts. When an
interrupt occurs, the context of the executing thread is saved and control is transferred to
the appropriate interrupt vector. An interrupt vector is an address for an interrupt service
routine (ISR) , which is user-written software designed to handle or service the needs of
a particular interrupt. There may be many ISRs, depending on the number of interrupts
that needs to be handled. The actual code required to service interrupts is necessarily
processor-specifi c.
3.12 Thread Starvation
One danger of preemptive, priority-based scheduling is thread starvation . This is a
situation in which threads that have lower priorities rarely get to execute because the
processor spends most of its time on higher-priority threads. One method to alleviate this
problem is to make certain that higher-priority threads do not monopolize the processor.
Another solution would be to gradually raise the priority of starved threads so that they
do get an opportunity to execute.
3.13 Priority Inversion
Undesirable situations can occur when two threads with different priorities share a
common resource.Priority inversion is one such situation; it arises when a higher-priority
thread is suspended because a lower-priority thread has acquired a resource needed by
the higher-priority thread. The problem is compounded when the shared resource is not
in use while the higher-priority thread is waiting. This phenomenon may cause priority

28 Chapter 3
inversion time to become nondeterministic and lead to application failure. Consider

In this example, Thread 3 (with the lowest priority) becomes ready. It obtains mutex M
and begins its execution. Some time later, Thread 2 (which has a higher priority) becomes
ready, preempts Thread 3, and begins its execution. Then Thread 1 (which has the highest
priority of all) becomes ready. However, it needs mutex M, which is owned by Thread 3,
so it is suspended until mutex M becomes available. Thus, the higher-priority thread (i.e.,
Thread 1) must wait for the lower-priority thread (i.e., Thread 2) before it can continue.
During this wait, the resource protected by mutex M is not being used because Thread
3 has been preempted by Thread 2. The concept of priority inversion is discussed more
thoroughly in Chapters 8 and 11.
3.14 Priority Inheritance
Priority inheritance is an optional feature that is available with ThreadX for use only
with the mutex services. (Mutexes are discussed in more detail in the next chapter.)
Priority inheritance allows a lower-priority thread to temporarily assume the priority of
a higher-priority thread that is waiting for a mutex owned by the lower-priority thread.
www.newnespress.com
Thread 2 becomes ready,
preempts Thread 3, and
proceeds with its processing
Thread 3 obtains mutex M
Thread 1 becomes ready
but suspends because it
needs mutex M
Even though Thread 1 has the highest
priority, it must wait for Thread 2.
Thus, priorities have become inverted.
Priority
Time
Figure 3.7: Example of priority inversion

RTOS Concepts and Defi nitions 29
www.newnespress.com
This capability helps the application to avoid nondeterministic priority inversion by
eliminating preemption of intermediate thread priorities. This concept is discussed more
thoroughly in Chapters 7 and 8.
3.15 Preemption-Threshold
Preemption-threshold
3
is a feature that is unique to ThreadX. When a thread is created,
the developer has the option of specifying a priority ceiling for disabling preemption.
This means that threads with priorities greater than the specifi ed ceiling are still allowed
to preempt, but those with priorities equal to or less than the ceiling are not allowed
to preempt that thread. The preemption-threshold value may be modifi ed at any time
during thread execution. Consider
threshold. In this example, a thread is created and is assigned a priority value of 20
and a preemption-threshold of 15. Thus, only threads with priorities higher than 15
(i.e., 0 through 14) will be permitted to preempt this thread. Even though priorities 15
through 19 are higher than the thread’s priority of 20, threads with those priorities will
not be allowed to preempt this thread. This concept is discussed more thoroughly in
Chapters 7 and 8.
Priority Comment
0
:
14
Preemption allowed for threads with priorities
from 0 to 14 (inclusive)
15
:
19
Thread is assigned preemption-threshold 15 [this has
the effect of disabling preemption for threads with priority
values from 15 to 19 (inclusive)]
20
:
31
Thread is assigned Priority 20
Figure 3.8: Example of preemption-threshold
3
Preemption-threshold is a trademark of Express Logic, Inc. There are several university research
papers that analyze the use of preemption-threshold in real-time scheduling algorithms. A complete
list of URLs for these papers can be found at 13 .

30 Chapter 3
3.16 Key Terms and Phrases
www.newnespress.com

asynchronous event ready thread
context switch Ready Thread List
cooperative multithreading round-robin scheduling
determinism RTOS
interrupt handling scheduling
kernel sleep mode
preemption suspended thread
preemption-threshold Suspended Thread List
priority thread starvation
priority inheritance time-slice
priority inversion timer-tick
3.17 Problems
1. When a thread is removed from the Suspended Thread List, either it is placed on
the Ready Thread List or it is terminated. Explain why there is not an option for
that thread to become the currently executing thread immediately after leaving the
Suspended Thread List.
2. Suppose every thread is assigned the same priority. What impact would this have on
the scheduling of threads? What impact would there be if every thread had the same
priority and was assigned the same duration time-slice?
3. Explain how it might be possible for a preempted thread to preempt its preemptor?
Hint: Think about priority inheritance.
4. Discuss the impact of assigning every thread a preemption-threshold value of 0 (the
highest priority).

www.newnespress.com
RTOS Building Blocks for System
Development
CHAPTER 4
4.1 Introduction
An RTOS must provide a variety of services to the developer of real-time embedded
systems. These services allow the developer to create, manipulate, and manage system
resources and entities in order to facilitate application development. The major goal of
this chapter is to review the services and components that are available with ThreadX.

4.2 Defi ning Public Resources
Some of the components discussed are indicated as being public resources. If a
component is a public resource, it means that it can be accessed from any thread. Note
that accessing a component is not the same as owning it. For example, a mutex can be
accessed from any thread, but it can be owned by only one thread at a time.
Threads Message queues
Counting
semaphores
Mutexes Event flags Memory block pools
Memory byte pools Application timers
Time counter and
interrupt control
Figure 4.1: ThreadX components

32 Chapter 4
4.3 ThreadX Data Types
ThreadX uses special primitive data types that map directly to data types of the
underlying C compiler. This is done to ensure portability between different C compilers.

meanings.
In addition to the primitive data types, ThreadX uses system data types to defi ne and
declare system resources, such as threads and mutexes.
these data types.
4.4 Thread
A thread is a semi-independent program segment. Threads within a process share the
same memory space, but each thread must have its own stack. Threads are the essential
building blocks because they contain most of the application programming logic. There is
www.newnespress.com
System data type System resource
TX_TIMER Application timer
TX_QUEUE Message queue
TX_THREAD Application thread
TX_SEMAPHORE Counting semaphore
TX_EVENT_FLAGS_GROUP Event flags group
TX_BLOCK_POOL Memory block pool
TX_BYTE_POOL Memory byte pool
TX_MUTEX Mutex
Figure 4.3: ThreadX system data types
Data type Description
UINT
Basic unsigned integer. This type must support 8-bit unsigned data;
however, it is mapped to the most convenient unsigned data type,
which may support 16- or 32-bit signed data.
ULONG Unsigned long type. This type must support 32-bit unsigned data.
VOID Almost always equivalent to the compiler’s void type.
CHAR Most often a standard 8-bit character type.
Figure 4.2: ThreadX primitive data types

RTOS Building Blocks for System Development 33
www.newnespress.com
no explicit limit on how many threads can be created and each thread can have a different
stack size. When threads are executed, they are processed independently of each other.
When a thread is created, several attributes need to be specifi ed, as indicated in
Figure 4.4
information critical to the internal processing of that thread. However, most applications
have no need to access the contents of the TCB. Every thread is assigned a name, which
is used primarily for identifi cation purposes. The thread entry function is where the
actual C code for a thread is located. The thread entry input is a value that is passed to
the thread entry function when it fi rst executes. The use for the thread entry input value is
determined exclusively by the developer. Every thread must have a stack, so a pointer to
the actual stack location is specifi ed, as well as the stack size. The thread priority must be
specifi ed but it can be changed during run-time. The preemption-threshold is an optional
value; a value equal to the priority disables the preemption-threshold feature. An optional
time-slice may be assigned, which specifi es the number of timer-ticks that this thread is
allowed to execute before other ready threads with the same priority are permitted to run.
Note that use of preemption-threshold disables the time-slice option. A time-slice value
of zero (0) disables time-slicing for this thread. Finally, a start option must be specifi ed
that indicates whether the thread starts immediately or whether it is placed in a suspended
state where it must wait for another thread to activate it.
Thread control block
Thread name
Thread entry input
Stack (pointer and size)
Priority
Preemption-threshold
Time-slice
Start option
Thread entry function
Figure 4.4: Attributes of a thread

34 Chapter 4
4.5 Memory Pools
Several resources require allocation of memory space when those resources are created.
For example, when a thread is created, memory space for its stack must be provided.
ThreadX provides two memory management techniques. The developer may choose
either one of these techniques for memory allocation, or any other method for allocating
memory space.
The fi rst of the memory management techniques is the memory byte pool, which is
illustrated in
collection of bytes that may be used for any of the resources. A memory byte pool is
similar to a standard C heap. Unlike the C heap, there is no limit on the number of
memory byte pools. In addition, threads can suspend on a pool until the requested
memory is available. Allocations from a memory byte pool are based on a specifi ed
number of bytes. ThreadX allocates from the byte pool in a fi rst-fi t manner, i.e., the fi rst
free memory block that satisfi es the request is used. Excess memory from this block
is converted into a new block and placed back in the free memory list, often resulting
infragmentation . ThreadX merges adjacent free memory blocks together during a
subsequent allocation search for a large enough block of free memory. This process is
calleddefragmentation .

have a Control Block that contains essential system information. Every memory byte
www.newnespress.com
Figure 4.5: Memory byte pool

RTOS Building Blocks for System Development 35
www.newnespress.com
pool is assigned a name, which is used primarily for identifi cation purposes. The starting
address of the byte pool must be provided, as well as the total number of bytes to be
allocated to the memory byte pool.
The second type of memory management technique is the memory block pool, which is
illustrated in xed-size memory blocks, so
there is never a fragmentation problem. There is a lack of fl exibility because the same
amount of memory is allocated each time. However, there is no limit as to how many
memory block pools can be created, and each pool could have a different memory block
size. In general, memory block pools are preferred over memory byte pools because the
fragmentation problem is eliminated and because access to the pool is faster.

must have a Control Block that contains important system information. Every memory
block pool is assigned a name, which is used primarily for identifi cation purposes. The
number of bytes in each fi xed-size memory block must be specifi ed. The address where
the memory block pool is located must be provided. Finally, the total number of bytes
available to the entire memory block pool must be indicated.
Memory byte pool control block
Memory byte pool name
Location of byte pool
Number of bytes allocated
Figure 4.6: Attributes of a memory byte pool
Fixed-size block
Fixed-size block
Fixed-size block
:
:
Fixed-size block
Figure 4.7: Memory block pool

36 Chapter 4
The total number of memory blocks in a memory block pool can be calculated as follows:
Total Number of Blocks
Total Number of Bytes Available
Number of By

( t tes in Each Memory Block sizeof void)( ( *))
Each memory block contains one pointer of overhead that is invisible to the user and is
represented by thesizeof (void*) expression in the preceding formula. Avoid wasting
memory space by correctly computing the total number of bytes to allocate, based on the
number of desired memory blocks.
4.6 Application Timer
Fast response to asynchronous external events is the most important function of real-time,
embedded applications. However, many of these applications must also perform certain
activities at predetermined intervals of time. Application timers enable applications to execute
application C functions at specifi c intervals of time. It is also possible for an application timer
to expire only once. This type of timer is called a one-shot timer, while repeating interval
timers are calledperiodic timers . Each application timer is a public resource.

have a Control Block that contains essential system information. Every application timer
is assigned a name, which is used primarily for identifi cation purposes. Other attributes
include the name of the expiration function that is executed when the timer expires.
Another attribute is a value that is passed to the expiration function. (This value is for
www.newnespress.com
Memory block pool control block
Memory block pool name
Number of bytes in each memory block
Location of memory block pool
Total number of bytes available
Figure 4.8 : Attributes of a memory block pool

RTOS Building Blocks for System Development 37
www.newnespress.com
the use of the developer.) An attribute containing the initial number of timer-ticks
1
for
the timer expiration is required, as is an attribute specifying the number of timer-ticks
for all timer expirations after the fi rst. The last attribute is used to specify whether the
application timer is automatically activated at creation, or whether it is created in a
nonactive state that would require a thread to start it.
Application timers are very similar to ISRs, except the actual hardware implementation
(usually a single periodic hardware interrupt is used) is hidden from the application.
Such timers are used by applications to perform time-outs, periodic operations, and/
or watchdog services. Just like ISRs, application timers most often interrupt thread
execution. Unlike ISRs, however, application timers cannot interrupt each other.
4.7 Mutex
The sole purpose of a mutex is to provide mutual exclusion; the name of this concept
provides the derivation of the name mutex (i.e., MUTual EXclusion).
2
A mutex is used
Application timer control block
Application timer name
Expiration function to call
Expiration input value to pass to function
Initial number of timer-ticks
Reschedule number of timer-ticks
Automatic activate option
Figure 4.9: Attributes of an application timer
1
The actual time between timer-ticks is specifi ed by the application, but 10 ms is the value used here.
2
In the 1960s, Edsger Dijkstra proposed the concept of a mutual exclusion semaphore with two
operations: the P operation (Prolaag, meaning to lower) and the V operation (Verhogen, meaning
to raise). The P operation decrements the semaphore if its value is greater than zero, and the V
operation increments the semaphore value. P and V are atomic operations.

38 Chapter 4
to control the access of threads to critical section or certain application resources. A
mutex is a public resource that can be owned by one thread only. There is no limit on the
number of mutexes that can be defi ned.
of a mutex.
Every mutex must have a Control Block that contains important system information.
Every mutex is assigned a name, which is used primarily for identifi cation purposes.
The third attribute indicates whether this mutex supports priority inheritance. Priority
inheritance allows a lower-priority thread to temporarily assume the priority of a
higher-priority thread that is waiting for a mutex owned by the lower-priority thread.
This capability helps the application to avoid nondeterministic priority inversion by
eliminating preemption of intermediate thread priorities. The mutex is the only ThreadX
resource that supports priority inheritance.
4.8 Counting Semaphore
A counting semaphore is a public resource. There is no concept of ownership of
semaphores, as is the case with mutexes. The primary purposes of a counting semaphore
are event notifi cation, thread synchronization, and mutual exclusion.
3
ThreadX
provides 32-bit counting semaphores where the count must be in the range from 0 to
4,294,967,295 or 2
32
– 1 (inclusive). When a counting semaphore is created, the count
must be initialized to a value in that range. Each value in the semaphore is an instance of
that semaphore. Thus, if the semaphore count is fi ve, then there are fi ve instances of that
semaphore.
www.newnespress.com
Mutex control block
Mutex name
Priority inheritance option
Figure 4.10: Attributes of a mutex
3
In this instance, mutual exclusion is normally achieved with the use of a binary semaphore, which
is a special case of a counting semaphore where the count is restricted to the values zero and one.

RTOS Building Blocks for System Development 39
www.newnespress.com

must have a Control Block that contains essential system information. Every counting
semaphore is assigned a name, which is used primarily for identifi cation purposes. Every
counting semaphore must have a Semaphore Count that indicates the number of instances
available. As noted above, the value of the count must be in the range from 0x00000000
to 0xFFFFFFFF (inclusive). A counting semaphore can be created either during
initialization or during run-time by a thread. There is no limit to the number of counting
semaphores that can be created.
4.9 Event Flags Group
An event fl ags group is a public resource. Event fl ags provide a powerful tool for thread
synchronization. Each event fl ag is represented by a single bit, and event fl ags are
arranged in groups of 32. When an event fl ags group is created, all the event fl ags are
initialized to zero.
ags group. Every event fl ags group must
have a Control Block that contains essential system information. Every event fl ags group
is assigned a name, which is used primarily for identifi cation purposes. There must also
be a group of 32 one-bit event fl ags, which is located in the Control Block.
Event flags group control block
Event flags group name
Group of 32 one-bit event flags
Figure 4.12 : Attributes of an event fl ags group
Counting semaphore control block
Counting semaphore name
Semaphore count
Figure 4.11: Attributes of a counting semaphore

40 Chapter 4
Event fl ags provide a powerful tool for thread synchronization. Threads can operate on all 32
event fl ags at the same time. An event fl ags group can be created either during initialization or
during run-time by a thread. Figure 4.13 contains an illustration of an event fl ags group after it
has been initialized. There is no limit to the number of event fl ags groups that can be created.
4.10 Message Queue
A message queue is a public resource. Message queues are the primary means of
interthread communication. One or more messages can reside in a message queue. A
message queue that holds a single message is commonly called amailbox . Messages are
placed at the rear of the queue,
4
and are removed from the front of the queue.

Control Block that contains essential system information. Every message queue is assigned
a name, which is used primarily for identifi cation purposes. Other attributes include the
message size, the address where the message queue is located, and the total number of
bytes allocated to the message queue. If the total number of bytes allocated to the message
queue is not evenly divisible by the message size, then the remaining bytes are not used.

in the queue (if space is available) and any thread may remove a message from a queue. www.newnespress.com
Message queue control block
Message queue name
Size of each message
Location of message queue
Total size of the message queue
Figure 4.14 : Attributes of a message queue
0
313029282726252423222120191817161514131211109876543210
00000 00000000000000000000000000
Figure 4.13: An event fl ags group
4
It is also possible to insert a message at the front of the queue.

RTOS Building Blocks for System Development 41
www.newnespress.com
Messages inserted at rear of queue Messages removed from front of queue
message_n message_3 message_2 message_1
Figure 4.15: A message queue
Mutex Counting semaphore
Speed
Somewhat slower than a
semaphore
A semaphore is generally faster
than a mutex and requires fewer
system resources
Thread ownership
Only one thread can own a
mutex
No concept of thread ownership for
a semaphore – any thread can
decrement a counting semaphore if
its current count exceeds zero
Priority
inheritance
Available only with a mutex
Feature not available for
semaphores
Mutual exclusion
Primary purpose of a mutex – a
mutex should be used only for
mutual exclusion
Can be accomplished with the use
of a binary semaphore, but there
may be pitfalls
Inter-thread
synchronization
Do not use a mutex for this
purpose
Can be performed with a
semaphore, but an event flags
group should be considered also
Event notification
Do not use a mutex for this
purpose
Can be performed with a
semaphore
Thread
suspension
Thread can suspend if another
thread already owns the mutex
(depends on value of wait
option)
Thread can suspend if the value of
a counting semaphore is zero
(depends on value of wait option)
Figure 4.16: Comparison of a mutex with a counting semaphore
4.11 Summary of Thread Synchronization and
Communication Components
Similarities exist between a mutex and a counting semaphore, especially when
implementing mutual exclusion. In particular, a binary semaphore has many of the same
properties as that of a mutex.
and recommendations as to how each should be used.

42 Chapter 4
application timer mutex ownership
binary semaphore mutual exclusion
Control Block one-shot timer
counting semaphore periodic timer
defragmentation preemption
entry function preemption-threshold
event fl ags group primitive data type
event notifi cation priority
fi rst-fi t allocation priority inheritance
fragmentation public resource
heap service call
ISR stack
mailbox system data type
memory block pool thread
memory byte pool thread suspension
message queue thread synchronization
mutex watchdog timer
We discussed four public resources that a thread can use for various purposes, as well as
four types of situations where each can be useful.
recommended uses of these resources.
4.12 Key Terms and Phrases
www.newnespress.com
Thread
synchronization
Event
notification
Mutual
exclusion
Inter-Thread
communication
Mutex Preferred
Counting
semaphore
OK – better for
one event
Preferred OK
Event flags
group
Preferred OK
Message
queue
OK OK Preferred
Figure 4.17: Recommended uses of resources

RTOS Building Blocks for System Development 43
www.newnespress.com
4.13 Problems
1. Explain why the special primitive data types UINT, ULONG, VOID, and CHAR are
used for service calls, rather than the standard C primitive data types.
2. What is the purpose of the thread entry function?
3. Under what circumstances would you use a binary semaphore rather than a mutex for
mutual exclusion?
4. There is only one public resource that can be owned by a thread. Which resource is
that?
5. Suppose you have a choice in using either a memory byte pool or a memory block
pool. Which should you choose? Justify your answer.
6. What does it mean to get an instance of a counting semaphore?
7. What is the maximum number of numeric combinations that can be represented by an
event fl ags group?
8. Messages are usually added to the rear of a message queue. Why would you want to
add a message to the front of a message queue?
9. Discuss the differences between a one-shot timer and a periodic timer.
10. What is a timer-tick?

www.newnespress.com
Introduction to the MIPS
Microprocessor
CHAPTER 5
5.1 Introduction
The MIPS microprocessor is one of the world’s most popular processors for embedded
applications. It can be found in applications ranging from hard disk controllers to laser-jet
printers to gaming consoles. The simplicity of the MIPS design is an important reason for
its success. A simpler processor is easier to use and frequently has faster performance.
Because of such features, MIPS is used in many modern products, including the
following:
set-top boxes disk drives
PDAs medical devices
digital cameras automobile navigation systems
ink and laser printers smart cards
switches and routers modems
wireless devices game consoles
5.2 History
The MIPS processor ancestry dates back to the pioneering days of RISC ( reduced
instruction set computer ) development in the early 1980s by John L. Hennessy of
Stanford University. Originally, the MIPS acronym stood for Microprocessor without
Interlocked Pipeline Stages , but the name is no longer considered an acronym today.
1
1
Depending on the specifi c processor, MIPS uses a three-stage, a fi ve-stage, or a six-stage
instruction pipeline. Branch instructions fl ush and refi ll the pipeline.

46 Chapter 5
www.newnespress.com
In 1984 Hennessy left Stanford and formed MIPS Computer Systems,
2
which focused on
the MIPS architecture. The fi rst MIPS processor was called the R2000 and was released
in 1985. In 1988, the R3000 was introduced and then the R4000 in 1991. The R4000
was the fi rst 64-bit MIPS microprocessor. The 1990s through the early 2000s also saw
the introduction of the R4400, R5000, R8000, R10000, R12000, RM7000, R14000, and
R16000.
Today, there are primarily two basic architectures of the MIPS core, the MIPS32 and the
MIPS64. The MIPS32 is somewhat similar to the R4000, but has 32-bit registers and
addressing, while the MIPS64 has 64-bit registers and addressing. In addition, there are
also hyperthreading versions of the MIPS cores, including the MIPS32 34K.
The MIPS microprocessor is a major success. Most people cannot go a day without using
a MIPS-based processor.
5.3 Technical Features
As mentioned previously, the MIPS architecture is based on the RISC concept. The
driving force behind RISC is that most high-level languages (such as C and C ) can be
implemented by using a small set of native processor instructions. When the number and
complexity of instructions is small, building the processor is much easier. Furthermore,
the processor requires much less power and can execute a simple instruction much faster
than a powerful but inherently complex instruction. Following are some basic attributes
of the MIPS architecture:
● Load-Store Architecture: Many MIPS instructions operate only on data already
stored in registers, which are inherently simple and fast operations. There is
a limited number of instructions that move data in memory to and from the
registers, thus reducing the complexity of the instruction set.
● Fixed Length Instructions: All MIPS instructions are either 4 bytes or 2
bytes (MIPS16 extension) in length. This eliminates the need to calculate the
instruction size and the potential for having to make multiple memory accesses to
complete a single instruction fetch.
● Orthogonal Registers: Most MIPS registers can be used for address or data.
2
The company is now known as MIPS Technologies, Inc.

Introduction to the MIPS Microprocessor 4 7
www.newnespress.com
● Single Cycle Execution: Most MIPS instructions execute in a single processor
cycle. Obvious exceptions include the load and store instructions mentioned
previously.
5.3.1 System-on-Chip (SoC) Compatibility
Miniaturization has been a trend for many years, especially in electronics. There are
many reasons for this phenomenon, but important reasons include the drive to reduce
the production cost of high-volume products, the need for reduced power consumption,
and the pursuit of improved effi ciency. Essentially, fewer raw materials translate to
lower production cost. In the embedded electronics industry, it has become popular to
place many components — processor, memory, and peripherals — on the same chip. This
technology is called System-on-Chip (SoC) and it is the primary reason that many devices,
such as cell phones, are so much smaller and less expensive than those of the past.
The simplicity of the MIPS architecture makes it a popular processor for SoC designs.
Even more important is the MIPS architecture licensing model adopted in the early
1990s. This model is designed and licensed for SoC applications, so major SoC
manufacturers commonly have MIPS licenses.
5.3.2 Reduced Power Consumption
Many consumer electronic products are battery powered. Accordingly, the underlying
processor and software must be very power effi cient. The MIPS architecture is
simpler and has fewer registers than most other RISC architectures. Because of these
characteristics, it requires less power. Another advantage that most MIPS products have
is a feature calledlow power mode . This is a power conservation state initiated by the
software when it determines there is nothing important to do. During the low power
mode, a small amount of power is used to keep the system coherent. When an interrupt
occurs, signaling the arrival of something important, the processor automatically returns
to its normal state of operation.
5.3.3 Improved Code Density
One common problem with RISC architectures is low code density . Code density is
a rough measure of how much work a processor can perform versus program size.
Because RISC instructions are simpler than those ofcomplex instruction set computers

Another Random Document on
Scribd Without Any Related Topics

the field panniers which serve as tables for instruments and
dressings.
It is needless to say that the operation-tent is very unlike an
operating theatre in a London hospital, but then the open veldt is
very unlike the Metropolis. The floor of the tent is much-trodden
grass, and, indeed, much-stained grass, for what drips upon it
cannot be wiped up. There are no bright brass water-taps, but there
is a brave display of buckets and tin basins. Water is precious, more
precious than any other necessity, for every drop has to be brought
by train from Frere.
There is little room in the tent for others than the surgeon, his
assistant, the anæsthetist, and a couple of orderlies. The surgeon is
in his shirtsleeves, and his dress is probably completed by riding
breeches and a helmet. The trim nurses, with their white caps and
aprons, who form the gentlest element in the hospital theatre, are
replaced by orderlies, men with burnt sienna complexions and
unshaven chins, who are clad in the unpicturesque army shirt, in
shorts, putties, and the inevitable helmet or "squasher" hat. They
are, however, strong in the matter of belts, which vary from a
leather strap or piece of string to an elaborate girdle, worked, no
doubt, by the hands of some cherished maiden. From the belt will
probably be hanging a big knife or a tin-opener, in place of the
nurse's chatelaine, and from the breeches pocket may be projecting
the bowl of a pipe. The orderly in a field hospital--who is for the
most part a "good sort"--look's a little like one of the dramatis
personæ of Bret Harte's tales, and is a curious substitute for the
immaculate dresser and the dainty nurse.

Still, appearances do not count for much, and the officers and
men of the Royal Army Medical Corps did as sterling good work on
December 15th as any body of men could do, and they were
certainly not hampered by the lack of a precise professional garb.
The wounded are brought into the marquee one by one. Not all
are cases for operation, but all have to be examined, and an
examination is more easily carried out on a table than on a stretcher
or the bare ground. Moreover, to make the examination painless, an
anæsthetic is usually required. I wonder how much chloroform and
morphia were used on that day, and on the night and day that
followed! The drugs would fill one scale of a balance in the other
scale of which would be found the dull weight of pain they were
destined to obliterate. The horrors of war are to some small extent
to be measured by the lists of the wounded and the dead, but a
more graphic representation would be provided by the hideous total
of the drops of chloroform and the grains of morphia which have
come from the surgeon's store.
The flies of the operation-marquee are wide open, for the heat
is intense, and access must be easy. As it is, there is much mopping
of brows and many "pulls" of dirty lukewarm water from precious
water-bottles. Unhappily the scenes within the shadow of the canvas
cannot be quite hidden from those who are lying in the sun outside
waiting their turn. As one man after another is carried in there is
sure to be some comrade on the ground who will call out as the
stretcher goes by: "Keep yer chivey up, Joe"; "Don't be down on
your luck"; "They will do you a treat"; "Good luck to yer, old cock,
you won't feel nothing."

One instance of the limited capacity of the marquee I may be
pardoned for recounting. The amputation of a leg was in progress
when the pressure of work was at its height. Beneath the table at
the time of the operation was the prostrate figure of a man. He had
been shot through the face. His big moustache was clotted with
blood, his features were obliterated by dust and blood, his eyes were
shut, and his head generally was enveloped in bandages. I thought
he was dead, and that in the hurry of events he was merely awaiting
removal. The limb after amputation was unfortunately dropped upon
this apparently inanimate figure when, to my horror, the head was
raised and the eyes were opened to ascertain the nature of the
falling body. This poor fellow was attended to as soon as the table
was free. I was glad to see him some weeks after in the Assembly
Hotel at Pietermaritzburg hearty and well. He was a gallant officer in
a Natal regiment, and when I recalled this gruesome incident to him,
he owned that, feeble as he was at the time, it gave him a "shake
up."
VII
THE SURGEONS OF THE FIELD HOSPITALS
Among the many officers of the R.A.M.C. I must confess that my
strongest sympathies are with those who are in charge of the little
field hospitals. These handy hospitals have their own transport, and
move with the various brigades or divisions. The officers who
command them have little comfort, little rest, the least luxurious

mess, and the hardest of work. They bear the brunt of the campaign
so far as the medical and surgical needs of the Army are concerned.
They must be always ready, always at hand, prepared to be full of
patients one day and empty the next; and those whose lives are
spent with them can certainly claim that they have "no abiding city."
The officers in charge of these hospitals are picked men, but as
sound experience is necessary they are often men who are no longer
young, and who may claim that they have already had their share of
roughing it. They are, perhaps, more than any others, the most
exposed to criticism. If anything goes wrong at the front a large
proportion of the blame falls upon them, and if all goes well their
names appear in no roll of honour.
No surgeon who saw these men could be other than proud that
he belonged to the same profession as they did. Of their work at
Colenso, at Spearman's Farm, and before Pieters I can only say that
it was, to my thinking, a credit to the medical department of any
army.
VIII
A PROFESSIONAL VISIT BY RAIL
After a busy afternoon among the field hospitals under the naval
ridge, I returned in the evening to Chieveley, in the hope, now that
the bulk of the work was over, of getting something to eat. I had not
been at Chieveley long when an orderly arrived with a letter to tell
me that Lieutenant Roberts had been brought in wounded, and to

ask me to go back to the naval hill at once. It was now dark, and I
had at that time no horse. However, the hospital train was standing
in the station, and to the fertile brain of Major Brazier-Creagh, who
was in charge of the train, it occurred that we might detach the
engine and go down on it to the ridge, since the field hospitals were
close to the railway.
There was the difficulty, however, that the line was a single line,
and a water train had already steamed down to the ridge, and was
expected back at any moment. It was the simple problem of an
engine on the one hand, and of a train on the other, proceeding in
different directions at night on a single line of rail.
The case being urgent, the engine was detached and we
started. Major Brazier-Creagh and Captain Symonds came with me.
It so happened that we went tender first. The railway line appeared
to us to go up and down with many undulations, and at the top of
each rise we expected to meet the water train. Fortunately the moon
was coming up, and the blackness which oppressed us was fading a
little. We proceeded slowly, with much whistling and considerable
waving of a red lamp. At last there was made out the dim outline of
the water train coming towards us at a fair speed. We stopped, and
there were redoubled efforts in the direction of whistling, lamp
waving, and shouting. These exhibitions had an immediate effect
upon the water train, which, after some hysterical whistling, stopped
and backed promptly out of sight. The driver told us afterwards that
he thought a whole train was coming down upon him at full speed,
and that he might well have backed down into Colenso.
We got out some way above the ridge and walked on to the
field hospital I had so lately left. The gallant officer I came to see

was comfortably bestowed in a tent, was quite free from pain and
anxiety, and was disposed to sleep. From a surgical point of view the
case was hopeless, and had been hopeless from the first, and no
idea of an operation could be entertained. Our examination and our
discussion of the case with Major Hamilton, R.A.M.C., under whose
care the patient was, occupied some time, and the engine had long
since gone back to Chieveley. There was nothing to be done but to
sleep on the ground in the open, and this we proceeded to do, lying
down on the grass outside the tent we had just visited. There was
no hardship in this, as it was a splendid night, and the full moon had
risen and had flooded the whole country with a spectral light.
As if by magic the restless, hurrying, motley crowd of the earlier
day had vanished. A cool breeze and pleasant shadows had replaced
the heat and the glare of the sun; a gentle silence had blotted out
the noise and the turmoil; and of the scene of the afternoon there
was nothing left but the white tents gleaming in the moon, the open
veldt, and the shadow of the ridge.
IX
THE HOSPITAL TRAIN AT COLENSO
The battle of Colenso was fought on Friday, December 15th, and on
Saturday, the 16th, an armistice was declared for the burying of the
dead. Very early on Saturday morning, while it was yet moonlight,
the hospital train backed down from Chieveley and came to a stand
as near the field hospitals as possible. As soon as it was daylight

(and at this time of the summer the sun rose before five) the loading
of the train commenced.
The filling up of a hospital train is no easy business, and affords
a somewhat depressing sight.
The worst cases are dealt with first, and a long line of stretchers
soon began to pour from the hospital tents to the railway. The
stretchers are put down on the railroad close to the wheels of the
train. On this particular morning it so happened that the carriages
threw a shadow on the side of the line towards the hospital, so that
the stretchers, if near the metals, were in the shade.
Many of the wounded had had no sleep, and many were
developing some degree of fever. A few had become delirious, and
were difficult to control. With the stretcher parties would come a
certain number of such of the wounded as could walk, and very
soon a not inconsiderable crowd was gathered in the shade of the
train.
But what a crowd! The same sunburnt men with blistered faces,
but now even a more motley gathering than filled the field hospitals
the day before--a gathering made piteously picturesque by khaki
rags, blue bandages, casual splints, arm slings, eye bandages, slit-up
trousers, and dressings of all kinds. Here they came crowding to the
train, some limping, some hopping, some helped along between two
stronger comrades, some staggering on alone. A man with a
damaged arm assisting a man with a bullet through his leg. A man
stopping on the way to be sick, cheered up by another with a
bandaged eye.
An untidy, sorrowful crowd, with unbuttoned tunics and slovenly
legs, with unlaced boots, with blood on their khaki jackets and on

their blue shirts and on their stiffening dressings. The gentle hand of
the nurse had not as yet busied itself with this unkempt and
unwashed throng. There had been no time for washing nor for
changing of garments, and if the surgeon has had to cut the coat
and the shirt into rags, the wearer must wear the rags or nothing;
and as for washing, it is a sin to wash when water is priceless.
The greater number of those who come to the railway line are
carried there on stretchers, but all who are well enough to take any
interest in the journey are eager not to miss a place in the train.
The business of getting the "lying down" cases into the
carriages is considerable, and everybody lends a hand, the surgeons
being the most active of any. The berths in the train are placed one
above the other, and the room for manipulating stretchers is small.
The equipment of the train was very complete, and every luxury was
at hand, from hot soup to iced "lemon-squash," and even to
champagne. Many generous ladies in the Colony had seen that the
train should want for nothing, and Major Brazier-Creagh took as
much pride in his travelling hospital as if he had built it himself.
Innumerable instances came under my notice of the
unselfishness of the soldier, and of his solicitude for his friends in
distress. It was by the side of this hospital train that occurred an
episode I have recorded elsewhere, and which may well be
described again. An orderly was bringing some water to a wounded
man lying on the ground near me. He was shot through the
abdomen, and he could hardly speak owing to the dryness of his
mouth, but he said: "Take it to my pal first, he is worse hit than me."
This generous lad died next morning, but his pal got through and is
doing well.

Another poor fellow, who was much troubled with vomiting, and
who was indeed dying, said, as he was being hoisted into the train,
"Put me in the lower berth, because I keep throwing up." How many
people troubled merely with sea-sickness would be as thoughtful as
he was? He died not long before we reached Chieveley.
Lieutenant Roberts, whom I had visited at intervals, went up by
this train, and was placed in No. 4 Field Hospital at Chieveley. Here a
bedstead, with a comfortable mattress and white sheets, was
waiting ready for him.
As the train moved off it was sad to note that a few who had
been brought down to the rail in the hope of a place being found for
them, had to be left behind, and had to be carried back to the tents
to await some other means of transport.
X
THE NURSES AT CHIEVELEY
The train which brought up No. 4 Field Hospital from Frere was
stopped, as I have already said, at Chieveley. The tents and baggage
were thrown out, and with as much haste as possible the hospital
was pitched on the open ground, close to the station. Before,
however, more than a few tents could be put up the wounded began
to arrive. They came in all Friday evening, and all Saturday, and all
Saturday evening. The field hospitals by the naval hill had soon been
filled, and all cases that could be sent on to Chieveley were sent

there, while as many as could go at once to the base were taken
down by the hospital train.
Saturday was a day of truce, but at sundown on Saturday not
only had all the wounded to be cleared out from the field hospitals,
but those hospitals themselves had to move, as, with the renewal of
hostilities, they would be in a place of danger. Chieveley was
therefore soon filled to overflowing.
There were three army surgeons with "No. 4" whose names I
have already mentioned. They were reinforced by a small field
hospital under the charge of Major Baird and Captain Begbie.
Some of the wounded came up by train, and some by
ambulances or by wagons, but a very large proportion, a proportion
which included nearly all the serious cases, were carried up on
stretchers by hand. No mode of transport is more comfortable than
this, or is less fatiguing to the patient, and the splendid organisation
of volunteer bearers and of coolie carriers enabled this means of
bringing up the wounded to be very largely made use of. Certainly
the stretcher-bearers were the means of saving lives, and of sparing
those they carried an infinite amount of pain.
As seen at night, the procession up to Chieveley was doleful and
mysterious. The long line of silent men moving in clusters, each
cluster with a stretcher and a body in its midst. Stealing slowly and
cautiously over the veldt in the moonlight, they all made for the two
white lights which swung over the hospital by the station.
The coolies carried their stretchers shoulder high, so that the
body of the man they bore was lit fitfully by the moon as they
passed along with absolutely noiseless feet. The coolies themselves
added no little to the uncanny spectacle, for in the shadow beneath

the stretcher stalked a double row of thin bare legs, and by the
poles of the stretcher were the white or coloured turbans that these
men affect; while here and there a sleek black head glistened in the
light.
There was but one house at Chieveley--the stationmaster's
house. It had been effectually looted after the Boer fashion, but it
would have done well as a resting-place for the four nurses who
came up with the hospital. The house, however, had been taken
possession of, and the nurses had to contemplate either a night in
the open or in the waiting-room at the station. As this latter room
had been used as a stable by the Boers, it was not in much request.
It served, however, as a place for the depositing of personal
baggage and for the preparing of such food as it was possible to
prepare--chiefly, indeed, for the making of tea.
The question of where to sleep was soon solved by the
necessities of the position. These ill-housed women, as a matter of
fact, were hard at work all Friday, all Saturday, and all Saturday
night. They seemed oblivious to fatigue, to hunger, or to any need
for sleep. Considering that the heat was intense, that the thirst
which attended it was distressing and incessant, that water was
scarce, and that the work in hand was heavy and trying, it was
wonderful that they came out of it all so little the worse in the end.
Their ministrations to the wounded were invaluable and beyond
all praise. They did a service during those distressful days which
none but nurses could have rendered, and they set to all at
Chieveley an example of unselfishness, self-sacrifice, and
indefatigable devotion to duty. They brought to many of the
wounded and the dying that comfort which men are little able to

evolve, or are uncouth in bestowing, and which belongs especially to
the tender, undefined and undefinable ministrations of women.
The English soldier is as sensible of attention and as
appreciative of sympathy and kindness as any other man who is at
the mercy of circumstances, and I can well believe that there are
many soldiers--some of them now in England, crippled for life--who
will long keep green the memory of the sisters at Chieveley.
Some weeks after Colenso I was at Pietermaritzburg, and was
looking up in the hospital wards certain cases which had been
attended to in "No. 4." Among them was a paralysed man to whom
one of the nurses had been very kind at Chieveley. I found him
comfortably bestowed, but he was possessed of a handkerchief the
extreme dirtiness of which led me to suggest that, as he was now in
a centre of luxury, he should ask for a clean one. To which he
replied, "I am not going to give this one up; I am afraid of losing it.
The sister who looked after me at Chieveley gave it to me, and here
is her name in the corner."
As the truce was over on Saturday, and as the Boers might
assume the aggressive and shell Chieveley and its helpless colony,
the order was given to break up the hospital and get all the
wounded away by train, and to retire with the tents and equipment
to Frere. This was done on Sunday morning.
As soon as the wounded had left--and it was no light matter
getting them away--it was thought desirable that the women should
be at once got out of danger, and so they were bundled down to
Frere with little ceremony in a mule wagon. As they had no hospital
to go to (for "No. 4" did not arrive until the small hours of the
following morning) they took refuge in the hotel at Frere. They had

some food with them, albeit it was not of a kind to attract the
fastidious, and the four of them slept on the floor of a looted and
empty room, which even the kindly heart of Mrs. Wilson could not
render other than a dreary resting place. This was their only "night
in" in three days.
I had, I am bound to confess, the advantage of them in the
matter of ventilation, for I slept in a wagon.
XI
SOME TRAITS IN THE MEN
As I have already said, the wounded took their turn of "hard luck"
like men. A few were sullen, a few relieved their feelings by fluent
but meaningless profanity, in which the Boers were cursed with as
much thoroughness as was the Jackdaw of Rheims. The majority
were silent or said little. The tendency of most of the men was to
make the least of their wounds, and some of those who were the
worst hit were the most cheery. They were, with scarcely an
exception, unselfish, and were singularly patient, considering that
the exercise of patience is not a marked quality in men.
They ministered to one another's wants with a tender solicitude
which was not marred by the occasional uncouthness of its method.
There was a wide-spread belief that tobacco was a panacea for all
ills, and any man who had the wherewithal to smoke shared the
small luxury with his mates. If there was only one pipe in a tent it
was kept circulating. One would see a man on one stretcher trying

to arrange a pillow for a comrade on the next: the pillow in question
being commonly made out of a squashed helmet with a boot inside
it. The man in any tent who was the least disabled was never so well
pleased as when he was given something to do for those who were
under the same canvas with him. With a pannikin and a spoon he
would feed those who could not feed themselves, until they were
glad to be rid of the attention; or he would readjust a dressing, or
cut off a boot, or get the dried blood from an exposed surface with a
never-wearying anxiety.
With few exceptions the men were honestly anxious "not to give
trouble." It was an article of faith with them to "take their turn," and
no man would try to make out that his case gave him a claim for
attention over his fellows. Indeed, on the occasion of a visit, the
occupants of a tent were eager with one voice to point out what
they considered to be the worst case, and to claim for it the earliest
notice. The men of a tent were, in the kindliest way, a little proud of
having a "real bad" case in their midst. When the curtain of a tent is
up the occupants whose heads are nearest to the tent ropes can
easily converse with those who are similarly placed in the adjoining
tent. Thus I heard one man on the ground, whose head was nearly
in the open, call out to another head just in view on the floor of the
next tent: "We've a real hot 'un in along with us; he's got 'it through
the lungs and the liver both, and the doctor has been in to him three
times." To which the other head replied: "That's nothing to a bloke
in here. He's been off his chump all night; his language has been a
fair treat, and he's had four fits. We've had a night, I don't think!"
Another article of faith with the soldier takes the form of a grim
stoicism under pain. Some of the wounded endured the examination

of their wounds with Spartan pluck. They seemed to consider it
above all things essential that they should not cry out "until they
were obliged." One enormous Irishman with a shattered thigh yelled
out in agony as he was being lifted upon the operating table to be
examined. The pain was evidently terrible and excuse enough for
any degree of exclamation. But he apologised quaintly and profusely
for the noise he made, urging as an excuse that "he had never been
in a hospital before." He expressed his regret much as a man would
do who had wandered into a church with his hat on and who
excused himself on the ground that he had never been in a church
before.
Every patient took a lively interest in his own case, and
especially in the removal of any bullet which may have lodged in any
part of him. One ruddy youngster, a Devonshire lad, had had a
shrapnel bullet through his leg, and the bullet could be felt, on the
side opposite to the point of entry, under the unbroken skin. He
begged that it should be taken out without chloroform, as he wanted
to see it come out and to keep it and take it home. He sat up with
his back against the tent pole during the operation, and watched the
cutting out of the lead without a murmur. No doubt this Boer missile
will find a place in a corner cupboard in some cottage among the
delectable villages of Devon, and will be for long the wonder and
admiration of devoted women folk.
Among other traits, one notices that the soldier clings with great
pertinacity to his few possessions, and especially to his boots. When
the haversack has been lost, and when the tunic has been cut up to
make its removal more easy, or left behind because it is too blood-
stained, there is little remaining in which the owner may bestow his

goods unless it be in his boots. There was one poor man I
remember at Spearman's, who was in great distress because, just as
he was being sent down to the base, he had lost his solitary boot.
He said it contained a puttie, a tin of jam, two shillings in money,
and a bullet that had been taken out of him. These are no mean
possessions.
The puttie also is not lightly discarded. If not used as a gaiter it
is useful for many other purposes, and especially is it considered
well to wind it round the abdomen as a cholera belt, for the soldier
has great faith in anything in the way of a belt.
When the men were bathing together in hundreds at
Springfield, there was an opportunity of seeing such variety in the
matter of abdominal belts as could never have been dreamed of.
Some of these favoured garments were mere shreds and rags, and
were worn probably in order to keep faith with some good soul at
home who had made her boy promise he would never leave off his
belt. Other binders were undoubtedly home-made, and the work of
anxious mothers and wives who believed in red flannel and plenty of
it. Some of the belts were knitted, and were made to be pulled on,
but they had shrunk so much from repeated wettings, and had
become so infantile in their proportions that the owner of the
garment had to get at least one comrade to help him pull it over his
hips. When it was at last in place it quite constricted the body, and
justified the comment of one bather, who exclaimed to his belted but
otherwise naked friend: "Well, ye've got a waist on ya, if nothink
else!"

XII
THE SIGN OF THE WOODEN CROSS
After Colenso, No. 4 Stationary Field Hospital returned to the same
quarters at Frere, and at Frere we remained until January 13th,
1900, nearly a month. The wounded who fell on the unhappy 15th
of December had been satisfactorily disposed of, thanks to the
admirable arrangements made by the Principal Medical Officer,
Colonel Gallwey, C.B. Not a single wounded man was left out on the
field on the night of the battle. On that particular Friday every man
had been attended to before midnight, and on the following Sunday
all the wounded who had fallen on the 15th were comfortably
housed in one or other of the hospitals at the base.
Our tents, although emptied of the wounded, soon began to be
filled up with cases of sickness, and especially with cases of
dysentery. Those who presented the slightest form of the disease
could be sent down to the base, but when the type was severe the
patient did better with as little movement as possible. Those,
therefore, who remained in our lines presented a large proportion of
examples of serious illness.
Provisions were ample, medical necessities abundant, and the
ladies of the Colony were infinitely kind in forwarding to Frere
comforts of all sorts. Our tents were by no means filled, and yet, in
spite of what may be considered favourable circumstances, there
were a good many deaths.
Deaths mean the need for burial, and a little burying ground
was marked off in the rear of the hospital, close to the railway line.
As weeks went by the little enclosure needed enlargement, and so

the engineers came and fenced it round afresh with a wire paling,
and gave it a fit aspect of formality. The names of the dead were
indicated on tablets of wood, and now and then the comrades of a
man, or the survivors of the tent he died in, would erect over the
mound a wooden cross.
These crosses were made usually out of provision boxes, or
perhaps from a whisky case, and many were very admirably finished
and very cleverly carved, and many were curious of design. They
represented long hours spent in tedious hacking at a tough slab of
wood with a pocket-knife, and, after that, infinite patience in the
cutting out of the letters of the dead chum's name. Finish would be
given to the lettering by means of a tin-opener.
These crosses will be found all over the land of the war. Few of
them will long survive the wind and the rain and the blistering sun,
and the hand of the Kaffir who is lacking of fuel. So long, however,
as they dot the solitary veldt they will be symbols of the tenderest
spirit of good comradeship, of the kindly heart of men who are
supposed to be little imbued with sentiment, and of that loyal
affection for his friend which is not among the least of the qualities
of the British soldier.
Here and there some elaborate monuments with some promise
of permanency have been erected. There is one, for example, in
which the inscription is fashioned out of empty cartridge cases stuck
into cement. There is another carved with some art out of stone.
I think, however, that those sleep best who lie beneath the
wooden cross fashioned with labour and some occasional dimness of
eye by the pocket-knife of an old "pal."

XIII
THE MEN WITH THE SPADES
The graves at Frere were dug by our own men, or rather by a small
fatigue party from a regiment near by. Nearly every morning they
came, the men with the spades. There were six of them, with a
corporal, and they came up jauntily, with their spades on their
shoulders and with pipes in their mouths. They were in their shirt-
sleeves, and there was much display of belt and of unbuttoned neck.
Their helmets were apt to be stuck on their heads in informal
attitudes. They were inexpressibly untidy, and they made in their
march a loose, shambling suggestion of a procession.
They came past my tent about breakfast time, and every
morning I wondered whether the men with the spades would come,
since, when they came, I knew that a death had taken place in the
night, and wondered who it was.
As in some way symbols of death, as elements in the last
services to be rendered to the dead, the men with the spades filled
me with great curiosity. They came up cheerily, and when they
reached the outskirts of the hospital the corporal would call out to
any orderly he saw: "Well, nipper, how many have we got to dig to-
day?"
When they had finished they went by my tent on their way back
to camp: still the same untidy, shambling lot; still, as a rule,
smoking, and still with the appearance of being infectiously cheerful.
I know well enough, however, that there was little cheeriness
among these men with the spades. They were dull enough in their

inmost hearts. The soldier is much impressed by a burying and by
the formalities which surround the dead. And as he knows he must
not "give way" he is prone to cover his easily stirred feelings by an
attempt at a "devil-may-care" attitude, and by an assumption of
rollicking indifference. It is, however, a poorly executed pretence,
and it needed no exceptional acumen to see that in reality no small
shadow of unhappiness followed the little shuffling procession, in
spite of their pipes and their jauntily posed helmets and their
laboured jokes.
If a soldier's grave is to be dug by sympathising hands, let it be
dug by the hands of these very men with the spades.
XIV
THE MARCHING
On Friday, January 12th, Sir Redvers Buller left Frere, and on the
following day we took our second departure from that place. The
movement was to be to Springfield, some eighteen miles across the
veldt. No. 4 Field Hospital was now to leave the railway and trust to
transport by oxen and mules. The hospital was equipped to
accommodate a minimum of three hundred beds, and was made up
of sixty tents and ten marquees. The rank and file of the R.A.M.C.
numbered eighty-eight non-commissioned officers and men; the
staff was represented by three army surgeons, nine civil surgeons,
the two army sisters who had worked at Colenso, and my remaining
nurse, Miss McCaul. The other nurse, Miss Tarr, who came out with

me, was at Maritzburg, desperately ill with dysentery. She nearly lost
her life, and was scarcely convalescent when the time came for us to
return to England. Her unexpected recovery was largely due to the
skill of the doctor who looked after her (Dr. Rochfort Brown, of the
Assembly Hospital), and to the extraordinary kindness of a lady who
was waiting at Pietermaritzburg to join her husband, then locked up
with his regiment in Ladysmith.
The three nurses kept with the hospital, and did as good work
at Spearman's Farm, after Spion Kop and Vaal Krantz, and at
Chieveley, after Pieters, as they did on the occasion of Colenso. They
had no easy time, for from the day we began at Frere until the lull
after Ladysmith we pitched the hospital no less than six times; viz.,
twice at Frere, twice at Chieveley, once at Spearman's, and once at
Springfield.
Our train was composed of sixteen ox wagons, each with
sixteen oxen, so that the number of oxen employed was over 260.
There were besides five ambulances, each drawn by ten mules. The
transport provided me consisted of a small covered wagon, a Scotch
cart, sixteen mules, a conductor on horseback, four Kaffir "boys," a
groom, and my own horse and manservant.
On the occasion of our leaving Frere on January 13, we were
roused at 3 A.M., while it was yet quite dark, and while the Southern
Cross was still ablaze in the sky. All the tents were struck by the
ungenial hour of 4 A.M. Packing up and the circumstances of
removal were conducted with difficulty and no little confusion. The
ox teams were lying about, and only a precarious light was furnished
by the lanterns we carried. It required no exceptional carelessness to
allow a wanderer in the camp to fall, in the course of a few minutes,

over a prostrate ox, a rolled-up tent, a pannier, a pile of cooking-
pots, or a derelict saddle. When the dawn came an agreeable sense
of order was restored, and we started on the march at 5 A.M.
There was a splendid sunrise, and the day proved a glorious
one, although it was painfully hot. The road was a mere track across
the veldt, which had been worn smooth in some places and cut into
ruts in others by the hundreds of wagons and the great array of
guns which had already passed over it.
"No. 4" formed a long convoy by the time the last wagon had
rumbled out of Frere. The pace was very slow, for the ox moves with
ponderous lethargy. The surgeons rode by the side of the train, the
sergeants and the orderlies walked as they listed, and the nurses
rode in ambulances, to the great shaking of their bodies. With us
were a hundred coolies, who were attached to the hospital for camp
work. They were a dismal crowd as they stalked along, with their
thin, bare legs and their picturesque tatters of clothing, with all their
earthly possessions in bundles on their heads, and with apparently a
vow of funereal silence in their hearts.
The heat soon became intense, and the march blank and
monotonous. There was ever the same shadeless veldt, the same
unending brown road, relieved by nothing but an occasional dead
horse or mule; the same creeping, creaking, wallowing wagons, the
never-absent perspiring Kaffirs, the everlasting cloud of dust, and
over all the blazing sun that neither hat nor helmet could provide
shelter from.
At 7.30 A.M. we reached a spot on the veldt known as Pretorius'
Farm. It was marked by what was called, with reckless imagery, a
stream, but which was represented by a wide and squalid gutter

Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com