Operating systems and middleware supporting controlled interaction Max Hailperin pdf download
Operating systems and middleware supporting controlled interaction Max Hailperin pdf download
https://ebookgate.com/product/operating-systems-and-middleware-
supporting-controlled-interaction-max-hailperin/
https://ebookgate.com/product/computer-systems-an-integrated-
approach-to-architecture-and-operating-systems-umakishore-
ramachandran/
https://ebookgate.com/product/operating-systems-design-and-
implementation-3rd-edition-andrew-s-tanenbaum/
https://ebookgate.com/product/operating-systems-internals-and-
design-principles-7th-ed-edition-stallings/
https://ebookgate.com/product/operating-systems-a-spiral-
approach-1st-edition-ramez-elmasri/
Advanced Concepts in Operating Systems Indian Edition
Mukesh Singhal
https://ebookgate.com/product/advanced-concepts-in-operating-
systems-indian-edition-mukesh-singhal/
https://ebookgate.com/product/advanced-operating-systems-and-
kernel-applications-techniques-and-technologies-1st-edition-yair-
wiseman/
https://ebookgate.com/product/operating-systems-principles-and-
practice-vol-3-memory-management-2nd-edition-thomas-anderson/
https://ebookgate.com/product/the-handbook-of-mobile-
middleware-1st-edition-paolo-bellavista/
https://ebookgate.com/product/data-hiding-exposing-concealed-
data-in-multimedia-operating-systems-mobile-devices-and-network-
protocols-1st-edition-michael-t-raggo/
Operating Systems and Middleware:
Supporting Controlled Interaction
Max Hailperin
Gustavus Adolphus College
or send a letter to Creative Commons, 171 Second Street, Suite 300, San
Francisco, California, 94105, USA.
To my family
iv
Contents
Preface xi
1 Introduction 1
1.1 Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 What Is an Operating System? . . . . . . . . . . . . . . . . . 2
1.3 What is Middleware? . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Objectives for the Book . . . . . . . . . . . . . . . . . . . . . 8
1.5 Multiple Computations on One Computer . . . . . . . . . . . 9
1.6 Controlling the Interactions Between Computations . . . . . . 11
1.7 Supporting Interaction Across Time . . . . . . . . . . . . . . 13
1.8 Supporting Interaction Across Space . . . . . . . . . . . . . . 15
1.9 Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2 Threads 21
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.2 Example of Multithreaded Programs . . . . . . . . . . . . . . 23
2.3 Reasons for Using Concurrent Threads . . . . . . . . . . . . . 27
2.4 Switching Between Threads . . . . . . . . . . . . . . . . . . . 30
2.5 Preemptive Multitasking . . . . . . . . . . . . . . . . . . . . . 37
2.6 Security and Threads . . . . . . . . . . . . . . . . . . . . . . . 38
3 Scheduling 45
3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.2 Thread States . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
3.3 Scheduling Goals . . . . . . . . . . . . . . . . . . . . . . . . . 49
3.3.1 Throughput . . . . . . . . . . . . . . . . . . . . . . . . 51
3.3.2 Response Time . . . . . . . . . . . . . . . . . . . . . . 54
3.3.3 Urgency, Importance, and Resource Allocation . . . . 55
3.4 Fixed-Priority Scheduling . . . . . . . . . . . . . . . . . . . . 61
v
vi CONTENTS
9 Networking 391
9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
9.1.1 Networks and Internets . . . . . . . . . . . . . . . . . 392
9.1.2 Protocol Layers . . . . . . . . . . . . . . . . . . . . . . 394
9.1.3 The End-to-End Principle . . . . . . . . . . . . . . . . 397
9.1.4 The Networking Roles of Operating Systems, Middle-
ware, and Application Software . . . . . . . . . . . . . 398
9.2 The Application Layer . . . . . . . . . . . . . . . . . . . . . . 399
9.2.1 The Web as a Typical Example . . . . . . . . . . . . . 399
CONTENTS ix
11 Security 473
11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
11.2 Security Objectives and Principles . . . . . . . . . . . . . . . 474
11.3 User Authentication . . . . . . . . . . . . . . . . . . . . . . . 480
11.3.1 Password Capture Using Spoofing and Phishing . . . . 481
11.3.2 Checking Passwords Without Storing Them . . . . . . 483
11.3.3 Passwords for Multiple, Independent Systems . . . . . 483
11.3.4 Two-Factor Authentication . . . . . . . . . . . . . . . 483
11.4 Access and Information-Flow Controls . . . . . . . . . . . . . 486
11.5 Viruses and Worms . . . . . . . . . . . . . . . . . . . . . . . . 491
11.6 Security Assurance . . . . . . . . . . . . . . . . . . . . . . . . 495
11.7 Security Monitoring . . . . . . . . . . . . . . . . . . . . . . . 497
11.8 Key Security Best Practices . . . . . . . . . . . . . . . . . . . 500
x CONTENTS
A Stacks 511
A.1 Stack-Allocated Storage: The Concept . . . . . . . . . . . . . 512
A.2 Representing a Stack in Memory . . . . . . . . . . . . . . . . 513
A.3 Using a Stack for Procedure Activations . . . . . . . . . . . . 514
Bibliography 517
Preface
Suppose you sit down at your computer to check your email. One of the
messages includes an attached document, which you are to edit. You click
the attachment, and it opens up in another window. After you start edit-
ing the document, you realize you need to leave for a trip. You save the
document in its partially edited state and shut down the computer to save
energy while you are gone. Upon returning, you boot the computer back
up, open the document, and continue editing.
This scenario illustrates that computations interact. In fact, it demon-
strates at least three kinds of interactions between computations. In each
case, one computation provides data to another. First, your email program
retrieves new mail from the server, using the Internet to bridge space. Sec-
ond, your email program provides the attachment to the word processor,
using the operating system’s services to couple the two application pro-
grams. Third, the invocation of the word processor that is running before
your trip provides the partially edited document to the invocation running
after your return, using disk storage to bridge time.
In this book, you will learn about all three kinds of interaction. In all
three cases, interesting software techniques are needed in order to bring the
computations into contact, yet keep them sufficiently at arm’s length that
they don’t compromise each other’s reliability. The exciting challenge, then,
is supporting controlled interaction. This includes support for computations
that share a single computer and interact with one another, as your email
and word processing programs do. It also includes support for data storage
and network communication. This book describes how all these kinds of
support are provided both by operating systems and by additional software
layered on top of operating systems, which is known as middleware.
xi
xii PREFACE
Audience
If you are an upper-level computer science student who wants to under-
stand how contemporary operating systems and middleware products work
and why they work that way, this book is for you. In this book, you will
find many forms of balance. The high-level application programmer’s view,
focused on the services that system software provides, is balanced with a
lower-level perspective, focused on the mechanisms used to provide those
services. Timeless concepts are balanced with concrete examples of how
those concepts are embodied in a range of currently popular systems. Pro-
gramming is balanced with other intellectual activities, such as the scientific
measurement of system performance and the strategic consideration of sys-
tem security in its human and business context. Even the programming
languages used for examples are balanced, with some examples in Java and
others in C or C++. (Only limited portions of these languages are used,
however, so that the examples can serve as learning opportunities, not stum-
bling blocks.)
outside resources beyond paper and pencil: you need just this textbook and
your mind. That does not mean all the exercises are cut and dried, however.
Some may call upon you to think creatively; for these, no one answer is cor-
rect. Programming projects require a nontrivial amount of programming;
that is, they require more than making a small, easily identified change in
an existing program. However, a programming project may involve other
activities beyond programming. Several of them involve scientific measure-
ment of performance effects, for example; these exploratory aspects may
even dominate over the programming aspects. An exploration project, on
the other hand, can be an experiment that can be performed with no real
programming; at most you might change a designated line within an ex-
isting program. The category of exploration projects does not just include
experimental work, however. It also includes projects that require you to do
research on the Internet or using other library resources.
Supplemental Resources
The author of this text is making supplemental resources available on his own
web site. Additionally, the publisher of the earlier first edition commissioned
additional resources from independent supplement authors, which may still
be available through the publisher’s web site and would largely still apply
to this revised edition. The author’s web site, http:// gustavus.edu/ +max/
os-book/ , contains at least the following materials:
• Source code in Java, C, or C++ for all programs that are shown in
the text
Acknowledgments
This book was made possible by financial and logistical support from my
employer, Gustavus Adolphus College, and moral support from my family.
I would like to acknowledge the contributions of the publishing team, espe-
cially developmental editor Jill Batistick and Product Manager Alyssa Pratt.
I am also grateful to my students for doing their own fair share of teaching.
I particularly appreciate the often extensive comments I received from the
following individuals, each of whom reviewed one or more chapters: Dan
Cosley, University of Minnesota, Twin Cities; Allen Downey, Franklin W.
Olin College of Engineering; Michael Goldweber, Xavier University; Ramesh
Karne, Towson University; G. Manimaran, Iowa State University; Alexander
Manov, Illinois Institute of Technology; Peter Reiher, University of Califor-
nia, Los Angeles; Rich Salz, DataPower Technology; Dave Schulz, Wisconsin
Lutheran College; Sanjeev Setia, George Mason University; and Jon Weiss-
man, University of Minnesota, Twin Cities. Although I did not adopt all
their suggestions, I did not ignore any of them, and I appreciate them all.
In preparing the revised edition, I took advantage of suggestions from
many readers. I would like to thank all of them, even those I’ve managed
to lose track of, to whom I also apologize. Those I can thank by name are
Joel Adams, Michael Brackney, Jack Briner, Justin Delegard, Ben Follis,
MinChan Kim, Finn Kuusisto, Matt Lindner, Milo Martin, Gabe Schmidt,
Fritz Sieker, and Alex Wauck.
xx PREFACE
Chapter 1
Introduction
1
2 CHAPTER 1. INTRODUCTION
remaining sections of this chapter are somewhat more focused. Each corre-
sponds to one or more of the later chapters and explains one important cat-
egory of service provided by operating systems and middleware. Section 1.5
explains how a single computer can run several computations concurrently,
a topic addressed in more depth by Chapters 2 and 3. Section 1.6 explains
how interactions between those concurrent computations can be kept under
control, the topic of Chapters 4 through 7. Sections 1.7 and 1.8 extend
the range of interacting computations across time and space, respectively,
through mechanisms such as file systems and networking. They preview
Chapter 8 and Chapters 9 and 10. Finally, Section 1.9 introduces the topic
of security, a topic I revisit at the end of each chapter and then focus on in
Chapter 11.
networking
Application Application Application
File
(a) (b)
other reason is because an operating system need not have this sort of user
interface at all. Consider again the case of an embedded system that con-
trols automotive fuel injection. If the system is sufficiently sophisticated,
it may include an operating system. The main control program may run
other, more specialized programs. However, there is no ability for the user
to start an arbitrary program running through a shell or desktop environ-
ment. In this book, I will draw my examples from general-purpose systems
with which you might be familiar, but will emphasize the principles that
could apply in other contexts as well.
stack, between the application programs and the operating system. Viewed
horizontally rather than vertically, middleware is also in the middle of in-
teractions between different application programs (possibly even running
on different computer systems), because it provides mechanisms to support
controlled interaction through coordination, persistent storage, naming, and
communication.
I already mentioned relational database systems as one example of mid-
dleware. Such systems provide a more sophisticated form of persistent stor-
age than the files supported by most operating systems. I use Oracle as my
primary source of examples regarding relational database systems. Other
middleware I will use for examples in the book includes the Java 2 Plat-
form, Enterprise Edition (J2EE) and IBM’s WebSphere MQ. These systems
provide support for keeping computations largely isolated from undesirable
interactions, while allowing them to communicate with one another even if
running on different computers.
The marketing definition of middleware doesn’t always correspond ex-
actly with my technical definition. In particular, some middleware is of
such fundamental importance that it is distributed as part of the operat-
ing system bundle, rather than as a separate middleware product. As an
example, general-purpose operating systems all come equipped with some
mechanism for translating Internet hostnames, such as www.gustavus.edu,
into numerical addresses. These mechanisms are typically outside the oper-
ating system kernel, but provide a general supporting service to application
programs. Therefore, by my definition, they are middleware, even if not
normally labeled as such.
Middleware Middleware
Database
Operating System Table Operating System
Figure 1.2: Middleware uses services from an operating system and in turn
provides services to application programs to support controlled interaction.
8 CHAPTER 1. INTRODUCTION
make more efficient use of a computer’s resources. For example, while one
computation is stalled waiting for input to arrive, another computation can
be making productive use of the processor.
A variety of words can be used to refer to the computations underway
on a computer; they may be called threads, processes, tasks, or jobs. In this
book, I will use both the word “thread” and the word “process,” and it is
important that I explain now the difference between them.
A thread is the fundamental unit of concurrency. Any one sequence of
programmed actions is a thread. Executing a program might create multiple
threads, if the program calls for several independent sequences of actions run
concurrently with one another. Even if each execution of a program creates
only a single thread, which is the more normal case, a typical system will be
running several threads: one for each ongoing program execution, as well as
some that are internal parts of the operating system itself.
When you start a program running, you are always creating one or more
threads. However, you are also creating a process. The process is a container
that holds the thread or threads that you started running and protects
them from unwanted interactions with other unrelated threads running on
the same computer. For example, a thread running in one process cannot
accidentally overwrite memory in use by a different process.
Because human users normally start a new process running every time
they want to make a new computation happen, it is tempting to think of
processes as the unit of concurrent execution. This temptation is ampli-
fied by the fact that older operating systems required each process to have
exactly one thread, so that the two kinds of object were in one-to-one corre-
spondence, and it was not important to distinguish them. However, in this
book, I will consistently make the distinction. When I am referring to the
ability to set an independent sequence of programmed actions in motion, I
will write about creating threads. Only when I am referring to the ability
to protect threads will I write about creating processes.
In order to support threads, operating system APIs include features such
as the ability to create a new thread and to kill off an existing thread. In-
side the operating system, there must be some mechanism for switching
the computer’s attention between the various threads. When the operating
system suspends execution of one thread in order to give another thread a
chance to make progress, the operating system must store enough informa-
tion about the first thread to be able to successfully resume its execution
later. Chapter 2 addresses these issues.
Some threads may not be runnable at any particular time, because they
are waiting for some event, such as the arrival of input. However, in general,
1.6. CONTROLLING THE INTERACTIONS BETWEEN COMPUTATIONS11
system kernel, others that are contained entirely within an application pro-
cess, and yet others that cross the boundary, providing support from within
the kernel for concurrent activities within the application process. Although
it might seem natural to discuss these categories of threads in Chapter 2, the
chapter on threads, I really need to wait for Chapter 7 in order to make any
more sense out of the distinctions than I’ve managed in this introductory
paragraph.
When two computations run concurrently on a single computer, the hard
part of supporting controlled interaction is to keep the interaction under con-
trol. For example, in my earlier example of a pair of threads, one produces
some data and the other consumes it. In such a situation, there is no great
mystery to how the data can flow from one to the other, because both are
using the same computer’s memory. The hard part is regulating the use of
that shared memory. This stands in contrast to the interactions across time
and space, which I will address in Sections 1.7 and 1.8. If the producer and
consumer run at different times, or on different computers, the operating
system and middleware will need to take pains to convey the data from one
to the other.
operations.
Either kind of file API provides a relatively simple interface to some quite
significant mechanisms hidden within the operating system. Chapter 8 also
provides a survey of some of these mechanisms.
As an example of a simple interface to a sophisticated mechanism, an
application programmer can make a file larger simply by writing additional
data to the end of the file. The operating system, on the other hand, has
to choose the location where the new data will be stored. When disks are
used, this space allocation has a strong influence on performance, because
of the physical realities of how disk drives operate.
Another job for the file system is to keep track of where the data for each
file is located. It also keeps track of other file-specific information, such as
access permissions. Thus, the file system not only stores the files’ data, but
also stores metadata, which is data describing the data.
All these mechanisms are similar to those used by middleware for pur-
poses such as allocating space to hold database tables. Operating systems
and middleware also store information, such as file directories and database
indexes, used to locate data. The data structures used for these naming and
indexing purposes are designed for efficient access, just like those used to
track the allocation of space to stored objects.
To make the job of operating systems and middleware even more chal-
lenging, persistent storage structures are expected to survive system crashes
without significant loss of integrity. For example, it is not acceptable after
a crash for specific storage space to be listed as available for allocation and
also to be listed as allocated to a file. Such a confused state must not occur
even if the crash happened just as the file was being created or deleted.
Thus, Chapter 8 builds on Chapter 5’s explanation of atomic transactions,
while also outlining some other mechanisms that can be used to protect the
integrity of metadata, directories, and indexes.
Persistent storage is crucially important, perhaps even more so in the
Internet age than in prior times, because servers now hold huge amounts of
data for use by clients all over the world. Nonetheless, persistent storage no
longer plays as unique a role as it once did. Once upon a time, there were
many computer systems in which the only way processes communicated was
through persistent storage. Today, that is almost unthinkable, because com-
munication often spans the Internet. Therefore, as I explain in Section 1.8,
operating systems provide support for networking, and middleware provides
further support for the construction of distributed systems.
1.8. SUPPORTING INTERACTION ACROSS SPACE 15
1.9 Security
Operating systems and middleware are often the targets of attacks by ad-
versaries trying to defeat system security. Even attacks aimed at application
programs often relate to operating systems and middleware. In particular,
easily misused features of operating systems and middleware can be the
root cause of an application-level vulnerability. On the other hand, operat-
ing systems and middleware provide many features that can be very helpful
in constructing secure systems.
A system is secure if it provides an acceptably low risk that an adversary
will prevent the system from achieving its owner’s objectives. In Chapter 11,
I explain in more detail how to think about risk and about the conflicting
objectives of system owners and adversaries. In particular, I explain that
some of the most common objectives for owners fall into four categories:
confidentiality, integrity, availability, and accountability. A system provides
confidentiality if it prevents inappropriate disclosure of information, integrity
if it prevents inappropriate modification or destruction of information, and
availability if it prevents inappropriate interference with legitimate usage. A
system provides accountability if it provides ways to check how authorized
users have exercised their authority. All of these rely on authentication, the
ability of a system to verify the identity of a user.
Many people have a narrow view of system security. They think of those
features that would not even exist, were it not for security issues. Clearly,
logging in with a password (or some other, better form of authentication) is
a component of system security. Equally clearly, having permission to read
some files, but not others, is a component of system security, as are crypto-
graphic protocols used to protect network communication from interception.
However, this view of security is dangerously incomplete.
You need to keep in mind that the design of any component of the
operating system can have security consequences. Even those parts whose
design is dominated by other considerations must also reflect some proactive
consideration of security consequences, or the overall system will be insecure.
In fact, this is an important principle that extends beyond the operating
system to include application software and the humans who operate it.
Therefore, I will make a habit of addressing security issues in every
chapter, rather than only at the end of the book. Specifically, each chapter
concludes with a section pointing out some of the key security issues asso-
ciated with that chapter’s topic. I also provide a more coherent treatment
of security by concluding the book as a whole with Chapter 11, which is
devoted exclusively to security. That chapter takes a holistic approach to
18 CHAPTER 1. INTRODUCTION
Exercises
1.1 What is the difference between an operating system and middleware?
1.4 What is one way an operating system might isolate threads from un-
wanted interactions, and what is one way that middleware might do
so?
1.5 What is one way an operating system might provide persistent storage,
and what is one way middleware might do so?
1.6 What is one way an operating system might support network commu-
nication, and what is one way middleware might do so?
1.7 Of all the topics previewed in this chapter, which one are you most
looking forward to learning more about? Why?
Programming Project
1.1 Write, test, and debug a program in the language of your choice to
carry out any task you choose. Then write a list of all the services
you suspect the operating system is providing in order to support the
execution of your sample program. If you think the program is also
relying on any middleware services, list those as well.
Exploration Projects
1.1 Look through the titles of the papers presented at several recent con-
ferences hosted by the USENIX Association (The Advanced Comput-
ing Systems Association); you can find the conference proceedings at
www.usenix.org. To get a better idea what an individual paper is
about, click the title to show the abstract, which is a short summary
of the paper. Based on titles and abstracts, pick out a few papers that
you think would make interesting supplementary reading as you work
1.9. SECURITY 19
your way through this book. Write down a list showing the biblio-
graphic information for the papers you selected and, as near as you
can estimate, where in this book’s table of contents they would be
appropriate to read.
Notes
The idea that an operating system should isolate computations from un-
wanted interactions, and yet support desirable interactions, has a long her-
itage. A 1962 paper [38] by Corbató, Daggett, and Daley points out that
“different user programs if simultaneously in core memory may interfere with
each other or the supervisor program so some form of memory protection
mode should be available when operating user programs.” However, that
same paper goes on to say that although “great care went into making each
user independent of the other users . . . it would be a useful extension of the
system if this were not always the case,” so that the computer system could
support group work, such as war games.
20 CHAPTER 1. INTRODUCTION
Threads
2.1 Introduction
Computer programs consist of instructions, and computers carry out se-
quences of computational steps specified by those instructions. We call
each sequence of computational steps that are strung together one after an-
other a thread. The simplest programs to write are single-threaded, with
instructions that should be executed one after another in a single sequence.
However, in Section 2.2, you will learn how to write programs that produce
more than one thread of execution, each an independent sequence of compu-
tational steps, with few if any ordering constraints between the steps in one
thread and those in another. Multiple threads can also come into existence
by running multiple programs, or by running the same program more than
once.
Note the distinction between a program and a thread; the program con-
tains instructions, whereas the thread consists of the execution of those
instructions. Even for single-threaded programs, this distinction matters.
If a program contains a loop, then a very short program could give rise
to a very long thread of execution. Also, running the same program ten
times will give rise to ten threads, all executing one program. Figure 2.1
summarizes how threads arise from programs.
Each thread has a lifetime, extending from the time its first instruc-
tion execution occurs until the time of its last instruction execution. If two
threads have overlapping lifetimes, as illustrated in Figure 2.2, we say they
are concurrent. One of the most fundamental goals of an operating sys-
tem is to allow multiple threads to run concurrently on the same computer.
That is, rather than waiting until the first thread has completed before a
21
22 CHAPTER 2. THREADS
Thread Thread A
Thread B
Spawn
Thread A Thread A
Thread B
Thread B
Sequential threads
second thread can run, it should be possible to divide the computer’s atten-
tion between them. If the computer hardware includes multiple processors,
then it will naturally be possible to run threads concurrently, one per pro-
cessor. However, the operating system’s users will often want to run more
concurrent threads than the hardware has processors, for reasons described
in Section 2.3. Therefore, the operating system will need to divide each pro-
cessor’s attention between multiple threads. In this introductory textbook
I will mostly limit myself to the case of all the threads needing to be run on
a single processor. I will explicitly indicate those places where I do address
the more general multi-processor case.
In order to make the concept of concurrent threads concrete, Section 2.2
shows how to write a program that spawns multiple threads each time the
program is run. Once you know how to create threads, I will explain in Sec-
tion 2.3 some of the reasons why it is desirable to run multiple threads con-
currently and will offer some typical examples of the uses to which threads
are put.
These first two sections explain the application programmer’s view of
threads: how and why the programmer would use concurrent threads. This
sets us up for the next question: how does the operating system support
the application programmer’s desire for concurrently executing threads? In
Sections 2.4 and 2.5, we will examine how the system does so. In this chap-
ter, we will consider only the fundamentals of how the processor’s attention
is switched from one thread to another. Some of the related issues I address
in other chapters include deciding which thread to run at each point (Chap-
ter 3) and controlling interaction among the threads (Chapters 4, 5, 6, and
7). Also, as explained in Chapter 1, I will wait until Chapter 7 to explain the
protection boundary surrounding the operating system. Thus, I will need
to wait until that chapter to distinguish threads that reside entirely within
that boundary, threads provided from inside the boundary for use outside of
it, and threads residing entirely outside the boundary (known as user-level
threads or, in Microsoft Windows, fibers).
Finally, the chapter concludes with the standard features of this book:
a brief discussion of security issues, followed by exercises, programming and
exploration projects, and notes.
tended to run in multiple threads, the original thread needs at some point
to spawn off a child thread that does some actions, while the parent thread
continues to do others. (For more than two threads, the program can repeat
the thread-creation step.) Most programming languages have an application
programming interface (or API) for threads that includes a way to create
a child thread. In this section, I will use the Java API and the API for
C that is called pthreads, for POSIX threads. (As you will see throughout
the book, POSIX is a comprehensive specification for UNIX-like systems,
including many APIs beyond just thread creation.)
Realistic multithreaded programming requires the control of thread in-
teractions, using techniques I show in Chapter 4. Therefore, my examples in
this chapter are quite simple, just enough to show the spawning of threads.
To demonstrate the independence of the two threads, I will have both
the parent and the child thread respond to a timer. One will sleep three
seconds and then print out a message. The other will sleep five seconds and
then print out a message. Because the threads execute concurrently, the
second message will appear approximately two seconds after the first. (In
Programming Projects 2.1, 2.2, and 2.3, you can write a somewhat more
realistic program, where one thread responds to user input and the other to
the timer.)
Figure 2.3 shows the Java version of this program. The main program
first creates a Thread object called childThread. The Runnable object asso-
ciated with the child thread has a run method that sleeps three seconds (ex-
pressed as 3000 milliseconds) and then prints a message. This run method
starts running when the main procedure invokes childThread.start(). Be-
cause the run method is in a separate thread, the main thread can continue
on to the subsequent steps, sleeping five seconds (5000 milliseconds) and
printing its own message.
Figure 2.4 is the equivalent program in C, using the pthreads API. The
child procedure sleeps three seconds and prints a message. The main proce-
dure creates a child_thread running the child procedure, and then itself
sleeps five seconds and prints a message. The most significant difference
from the Java API is that pthread_create both creates the child thread
and starts it running, whereas in Java those are two separate steps.
In addition to portable APIs, such as the Java and pthreads APIs, many
systems provide their own non-portable APIs. For example, Microsoft Win-
dows has the Win32 API, with procedures such as CreateThread and Sleep.
In Programming Project 2.4, you can modify the program from Figure 2.4
to use this API.
2.2. EXAMPLE OF MULTITHREADED PROGRAMS 25
Persia was once a great power in the world; the Persian religion, a
conquering and encroaching faith. The Persian Empire threatened to
destroy the independence of Greece. It held the Jews in actual
subjection, and its religious views profoundly influenced the
development of theirs. Through the Jews, its ideas have penetrated
the Christian world, and leavened Europe. It once possessed an
extensive and remarkable sacred literature, but a few scattered
fragments of which have descended to us. These fragments,
recovered and first translated by Anquetil du Perron, have been but
imperfectly elucidated as yet by European scholars; and there can be
no doubt that much more light remains to be cast upon them by
philology as it progresses. Such as they are, however, I shall make
use of the translations already before us to give my readers an
imperfect account of the character of the Parsee Scriptures.
These compositions are the productions of several centuries and
are widely separated from one another in the character of their
thought, and in the objects of worship proposed to the faithful
follower of Zarathustra. The oldest among them, which may belong
to the time of the prophet himself, are considered by Haug to be as
ancient as b.c. 1200, while the youngest were very likely as recent as
b.c. 500.
Haug considers the Avesta to be the most ancient text, while the
Zend was a kind of commentary upon this already sacred book.
Taking the several portions of the Zend-Avesta in their
chronological order (as far as this can be ascertained), we shall
begin with the five Gâthâs, which are pronounced by their translator
to be "by far the oldest, weightiest, and most important pieces of
the Zend-Avesta" (F. G., xiii). Some portions of these venerable
hymns are even attributed by him to Zarathustra himself; but this—
except where the prophet is in some way named as the author—
must be considered only as an individual opinion, which can carry no
positive conviction to other minds until it is supported by stronger
evidence than any at present accessible. Meantime, we may rest
assured that we possess among these hymns some undoubted
productions of the Zarathustrian age.
While the Gâthâs and the confession just quoted represent the
most ancient phase of the Mazdayaçna faith, we enter, in the
remaining portion of the Yaçna, on a much later stage of the
growing creed. So many new divinities, or at any rate, objects of
reverential addresses, now enter upon the scene, that we almost
lose sight of Ahura-Mazda in the throng of his attendants. We seem
to be some ages away from the days when Zarathustra bade his
hearers choose between the one true God and the multitude of false
gods worshiped by his enemies. Ahura-Mazda is safely enthroned,
and Zarathustra shines out gloriously as his prophet; but
Zarathustra's creed is overloaded with elements of which he himself
knew nothing. The first chapter of the Yaçna, a liturgical prayer,
brings these elements conspicuously before us. It is an invocation
and celebration of a great variety of powers belonging to what is
termed the good creation, or the world of virtuous beings and good
things, as opposed to the malicious beings and bad things who form
the realm of evil.[74] Thus it opens:—
"I invoke and I celebrate the creator Ahura-Mazda,
luminous, resplendent, very great and very good, very
perfect and very energetic, very intelligent and very
beautiful, eminent in purity, who possesses the excellent
knowledge, the source of pleasure; him who has created
us, who has formed us, who has nourished us, the most
accomplished of intelligent beings."[75]
Every verse, until we approach the end, commences with the
same formula:—"I invoke and I celebrate;" or, as Spiegel translates
it, "I invite and announce it;" the sole difference is in the beings
invoked. Many of these are powers of more or less eminence in the
Parsee spiritual hierarchy, but it would be going beyond our object
here to enumerate their names and specify their attributes. To a
large proportion of them the epithets "pure, lord of purity," are
added, while some are dignified with more special titles of honor.
After the above homage to Ahura-Mazda, the writer invokes and
celebrates, among others: Mithra (a very famous god), who
increases oxen, who has one thousand ears, and ten thousand eyes;
the fire of Ahura-Mazda; the water given by Ahura-Mazda; the
Fravashis (angels or guardian spirits) of holy men and of women
who are under men's protection; energy, with a good constitution
and an imposing figure; victory given by Ahura; the months; the
new moon; the full moon; the time of fecundation; the years; all the
lords of purity, and thirty-three genii surrounding Hâvani, who are of
admirable purity, whom Mazda has made known, and Zarathustra
has proclaimed; the stars, especially a star named Tistrya; the
moon, which contains the germ of the ox; the sun, the eye of Ahura-
Mazda; the trees given by Mazda; the Word made known by
Zarathustra against the Devas; the excellent law of the
Mazdayaçnas; the perfect benediction; the pure and excellent man;
these countries and districts; pastures and houses; the earth, the
sky, the wind; the great lord of purity; days, months, and seasons;
the Fravashis of the men of ancient law; those of contemporaries
and relations, and his own; all genii who ought to be invoked and
adored. It is manifest from this invocation, in which I have omitted
many names and many repetitions, how far we are from the stern
and earnest simplicity of the Gâthâs. Regular liturgical forms have
sprung up, and these express the more developed and complicated
worship which the Parsee priesthood has now engrafted on the
Zarathustrian monotheism.
The concluding verses run as follows:—
"O thou who art given in this world, given against the
Devas, Zarathustra[76] the pure, lord of purity, if I have
wounded thee, either in thought, word, or deed,
voluntarily or involuntarily, I again address this praise in
thine honor; yes, I invoke thee if I have failed against
thee in this sacrifice and this invocation.
"O all ye very great lords, pure, masters of purity, if I
have wounded you, &c. [as above].
"May I, a worshiper of Mazda, an adherent of
Zarathustra, an enemy of the Devas, an observer of the
precepts of Ahura, address my homage to him who is
given here, given against the Devas; to Zarathustra, pure,
lord of purity, for the sacrifice, for the invocation, for the
prayer that renders favorable, for the benediction. (May I
address my homage) to the lords (who are) the days, the
parts of days, &c., for the benediction; that is to say: (may
I address my homage) to the lords (who are) the days,
the parts of days, the months, the seasons of the year
(Gahanbârs), the years; for the sacrifice, for the
invocation, for the prayer that renders favorable, for the
benediction."[77]
The rest of the Yaçna consists mainly of praises or prayers
addressed to the very numerous objects of Parsee adoration, and
most of it is of little interest. The following short section, however,
deserves remark:—
Yaçna 12.
1. "I praise the thoughts rightly thought, the words
rightly spoken, and the deeds rightly done.
2. "I seize upon (or resort to) all good thoughts, words
and deeds.
3. "I forsake all bad thoughts, words, and deeds.
4. "I bring you, O Amesha-çpentas,
5. "Praise and adoration,
6. "With thoughts, words, and deeds, with heavenly
mind, the vital force from my own body."[78]
In the following verses again there is some excellence:—
1. "May that man attain that which is best who teaches
us the right way to our profit in this world, both the
material and the spiritual world, the plain way that leads
to the worlds where Ahura is enthroned, and the sacrificer,
resembling thee, a sage, a saint, O Mazda.
2. "May there come to this dwelling contentment,
blessing, fidelity, and the wisdom of the pure."
8. "In this dwelling may Çraosha[79] (obedience) put an
end to disobedience, peace to strife, liberality to avarice,
wisdom to error, truthful speech to lying, which detests
purity" (Av. ii. 186, 187.—Yaçna 59).
The prominent position occupied by fire in the Parsee faith is well
known. The presence of fire is indeed an essential part of their
ritual, in which it is treated with no less honor than the consecrated
wafer in that of Catholic Christians. Not only, however, is it employed
in their rites, but it is addressed as an independent being, to whom
worship is due. Not that its place in the hierarchy is to be
confounded with that of Ahura-Mazda. It is not put upon a level with
the supreme being, but it is addressed as his son, its rank being thus
still more closely assimilated to that of the host, which is in like
manner a part of the liturgical machinery and an embodiment of the
son of God. A special chapter of the Yaçna—the 61st—is devoted to
Fire, and a summary of its contents will help us to understand the
light in which this deity was regarded.
The sacrificer begins by vowing offerings and praise and good
nourishment to "Fire, son of Ahura-Mazda." He trusts that Fire may
ever be provided with a proper supply of wood, and may always
burn brightly in this dwelling, even till the final resurrection. He
beseeches Fire to give him much property, much distinction,
holiness, a ready tongue, wit and understanding, activity,
sleeplessness, and posterity. Fire is said to await nourishment from
all; whoever comes, he looks at his hands, saying: "What does the
friend bring his friend, the coming one to him who sits alone?" And
this is the blessing he bestows on him who brings him dry wood,
picked out for burning: "Mayest thou be surrounded with herds of
cattle, with abundance of men. May it be with thee according to the
desire of thy heart, according to the desire of thy soul. Be joyous,
live thy life the whole time that thou shalt live."[80]
The last chapter but one of the Yaçna is a hymn in universal praise
of the good creation. All the objects belonging to that creation—that
is, made by Ahura-Mazda, and standing in contrast with the bad
creation of Agra-Mainyus—are enumerated, and as a catalogue of
these the hymn is interesting. Ahura-Mazda himself is named first;
then Zarathustra; after this follows the Fravashi (angel) of
Zarathustra, the Amesha-çpentas, the Fravashis of the pure, and so
forth, through a long list of animate and inanimate beings. Each is
named with the formula "we praise" following the title, as: "The
whole earth we praise" (Av., vol. ii. p. 202.—Yaçna, 70).
So close is the resemblance between the Vispered and that
portion of the Yaçna which we have just examined, that it will be
needless to dwell upon the contents of the former. We may therefore
at once pass on to a very important section, for theological
purposes, of the Zend-Avesta, namely—
Subdivision 5.—Vendidad.
Totally unlike either the Yaçna, the Vispered, or the Yashts, the
Vendidad is a legislative code—dealing indeed largely with religious
questions, but not confining itself exclusively to them. It differs from
the remainder of the sacred volume much as Leviticus differs from
the Psalms, or as the Institutes of Menu differ from the hymns of the
Rig-Veda. It is regarded as equally holy with the rest of the Avesta,
and is recited in divine service along with Vispered and Yaçna, the
three together forming what is termed the Vendidad-Sade (Av., ii.
lxxv). Its abrupt termination indicates that the code is not before us
in its entirety; the portion which has been preserved, however, does
not appear to have suffered great mutilation. Let us briefly
summarize its contents, first premising that the form they assume
(with trifling exceptions) is that of conversations between Ahura-
Mazda and his prophet.
The first Fargard (or chapter) is an enumeration of the good
countries or places created by Ahura-Mazda, and of the evils—such
as the serpent, the wasp, and various moral offenses, including that
of doubt—created in opposition to him in each case by the president
of the bad creation, Agra-Mainyus. The second Fargard is a long
narrative of the proceedings of a mythological hero named Yima (the
Indian Yama), to whom Ahura-Mazda is stated to have once
committed the government of the world, or of some part of it. Thus
far we have not entered on the proper subject-matter of the
Vendidad. The third Fargard, while still introductory, approaches
more nearly to the subsequent chapters, alike in its form and its
contents. In it Zarathustra lays certain queries before Ahura-Mazda,
and the replies given by that deity are of high importance for the
comprehension of both the social and moral status of the Parsees at
the time when this dialogue was written. The stress laid upon the
virtue of cultivating the soil is especially to be noticed. Similar
sentiments are frequently repeated in the Vendidad, and indicate a
people among whom agriculture was still in its infancy, the transition
from the pastoral state to the more settled condition of tillers of the
soil being still incomplete. The compilers of this code evidently felt
strongly the extreme value to their youthful community of
agricultural pursuits, and therefore encouraged them at every
convenient opportunity by representing them as peculiarly
meritorious in the sight of God.
Zarathustra begins his inquiries by asking what is in the first place
most agreeable to this earth, and successively ascertains what are
the five things which give it most satisfaction, and what the five
which cause it the most displeasure. Ahura-Mazda answers that, in
the first place, a holy man with objects of sacrifice is the most
agreeable; then a holy man making his dwelling-place, and storing it
with all that pertains to a happy and righteous life; then the
production of grain and of fruit trees, the irrigation of thirsty land, or
the drainage of moist land; fourthly, the breeding of live-stock and
draught-cattle; fifthly, a special incident connected with the presence
of such animals on the land. The five displeasing things are, the
meetings of Daevas and Drujus (evil spirits), the interment of men or
dogs (which was contrary to the law), the accumulation of Dakhmas,
or places where the bodies of the dead were left exposed, the dens
of animals made by Agra-Mainyus, and lastly, unbecoming conduct
on the part of the wife or son of a holy man. Further questions are
then put as to the mode of conduct which wins the approbation of
the earth, and it is stated to consist in actions which tend to
counteract the evils above enumerated. In the course of these
replies occasion is again taken to eulogize the man who vigorously
cultivates the soil, and to censure him who idly leaves it
uncultivated. Certain penalties are then imposed on those who bury
dogs or men, but the sin of leaving them underground for two years
is declared to be inexpiable, except by the Mazdayaçna Law, which
can purify the worst offenders:—
"For it (the Law) will take away these (sins) from those
who praise the Mazdayaçna Law, if they do not again
commit wicked actions. For this the Mazdayaçna Law, O
holy Zarathustra, takes away the bonds of the man who
praises it. It takes away deceit. It takes away the murder
of a pure man. It takes away the burial of the dead. It
takes away inexpiable actions. It takes away accumulated
guilt. It takes away all sins which men commit" (Av., vol. i.
p. 87, 88.—Vendidad, iii. 140-148).
We see from this that the power of the Law to deliver sinners from
the burden of their offenses was in no way inferior to that of the
Atonement of Christ.
It is unnecessary to dwell upon the fourth Fargard, which deals
with the penalties—consisting mainly of corporal punishment—for
breach of contract and other offenses. The fifth and sixth, being
concerned with the regulations to be observed in case of impurity
arising from the presence of dead bodies, are of little interest. A
large part of the seventh is occupied with the same subjects, but its
course is interrupted by certain precautions to be attended to in the
graduation of students of medicine, which may be commended to
the notice of other religious communities. Should a Mazdayaçna
desire to become a physician, on whom, inquires Zarathustra, shall
he first try his hand, the Mazdayaçna (orthodox Parsees), or the
Daevayaçnas (adherents of a false creed)? Ahura-Mazda replies that
the Daevayaçnas are to be his first patients. If he has performed
three surgical operations on these heretics, and his three patients
have died, he is to be held unfit for the medical profession, and must
on no account presume to operate on the adherents of the Law. If,
however, he is successful with the Daevayaçnas, he is to receive his
degree, and may proceed to practice on the more valuable bodies of
faithful Parsees. So careful a contrivance to ensure that none but
infidels shall fall victims to the knife of the unskilful surgeon evinces
no little ingenuity.
The eighth Fargard relates chiefly to the treatment of dead bodies,
while the ninth proceeds to narrate the rites for the purification of
those who have come in contact with them. A terrible penalty—that
of decapitation—is enacted against the man who ventures to
perform this rite without having learnt the law from a priest
competent to purify. The tenth Fargard prescribed the prayers by
which the Drukhs, or impure spirit supposed to attach itself to
corpses, and to come from them upon the living, is to be driven
away: and the subject is continued in the eleventh, which contains
formularies for the purification of dwellings, fires, and other objects.
Along with injunctions as to the purification of houses where a death
has occurred, the twelfth Fargard informs its hearers how many
prayers they are to offer up for deceased relatives. The number
varies both according to their relationship, being highest for those
that are nearest akin, and according to their purity or sinfulness,
double as many being required for the sinful as for the pure. After a
short introduction expounding the merit of killing a certain species of
animal and the demerit of killing another (what they are is
uncertain), the thirteenth Fargard proceeds to enumerate in detail
the various kinds of offenses against dogs, and the corresponding
penalties. Dogs were evidently of the utmost importance to the
community, and their persons are guarded with scarcely less care
than those of human beings. They are held to have souls, which
migrate after their decease to a canine Paradise. It seems, too, that
shades of departed dogs are appointed to watch the dangerous
bridge over which men's souls must travel on the road to felicity, and
which the wicked cannot pass; for we are informed of the soul of a
man who has killed a watch-dog, that "the deceased dogs who
guard against crime and watch the bridge do not make friends with
it on account of its abominable and horrible nature" (Av., vol. i. p.
192.—Vendidad, xiii. 25); while a man who has killed a water-dog is
required to make "offerings for its pious soul for three days and
three nights" (Av., vol. i. p. 201.—Vendidad, xiii. 173). The place to
which the souls of these animals repair is termed "the water-
dwelling," and it is stated that two water-dogs meet them on their
arrival, apparently to welcome them to their aqueous heaven (Av.,
vol. i. p. 200.—Vendidad, xiii. 167). Not only killing dogs, but
wounding them or giving them bad food, are crimes to be severely
punished; and even in case of madness the dog's life is on no
account to be taken. On the contrary, the utmost care is to be taken,
by fastening him so as to prevent escape, that he should do himself
no injury, for if he should happen in his madness to fall into water
and die, the community will have incurred sin by the accident.[81]
The following verses convey an interesting notion of the esteem in
which the dog was held among the early Parsees. The speaker is
Ahura-Mazda:—
"I have created the dog, O Zarathustra, with his own
clothes and his own shoes; with a sharp nose and sharp
teeth; attached to mankind, for the protection of the
herds. Then I created the dog, even I Ahura-Mazda, with
a body capable of biting enemies. When he is in good
health, when he is with the herds, when he is in good
voice, O holy Zarathustra, there comes not to his village
either thief or wolf to carry off property unperceived from
the villages" (Av., vol. i. p. 197.—Vendidad, xiii. 106-113).
In the fourteenth Fargard, water-dogs are further protected
against wounds; while in the fifteenth, the preservation of the canine
species at large is ensured by elaborate enactments. To give a dog
bones which he cannot gnaw, or food so hot as to burn its tongue, is
a sin; to frighten a bitch in pup, as by clapping the hands, is likewise
to incur guilt; and they are gravely criminal who suffer puppies to
die from inattention. If born in camel-stalls, stables, or any such
places, it is incumbent on the proprietor to take charge of them; or,
if the litter should be at large, at least the nearest inhabitant is
bound to become their protector. Strangely intermingled with these
precautions are rules prohibiting cohabitation with women in certain
physical conditions, and enactments for the prevention of abortion,
and for ensuring the support of a pregnant girl by her seducer, at
least until her child is born. The crime of abortion is described in a
manner which curiously reveals the practices occasionally resorted to
by Parsee maidens. Should a single woman be with child, and say,
"The child was begotten by such and such a man"—
"If then this man says, 'Try to make friends with an old
woman and inquire of her; if then this girl does make
friends with an old woman, and inquire of her, and this old
woman brings Baga, or Shaêta, or Ghnâna, or Fraçpâta, or
any of the vegetable purgatives, saying, 'Try to kill this
child;' if then the girl does try to kill the child, then the
girl, the man, and the old woman are equally criminal."
Neither the sixteenth nor the seventeenth Fargard need detain us.
They relate, the one to the above-mentioned rules to be observed
towards women, the other to the disposal of the hair and nails,
which are held to pollute the earth. The eighteenth Fargard begins,
as if in the middle of a conversation, with an address by Ahura-
Mazda, on the characteristics of true and false priests, some, it
appears, having improperly pretended to the priesthood. After some
questions on other points of doctrine put by Zarathustra, we are
suddenly introduced to a conversation between the angel Çraosha
and the Drukhs, or evil spirit, in which the latter describes the
several offenses that cause her to become pregnant, or, in other
words, increase her influence in the world. After this interlude, we
return to Ahura-Mazda and Zarathustra. The prophet, having been
exhorted to put questions, inquires of his god who causes him the
greatest annoyance. Ahura-Mazda replies that it is "he who mingles
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com