(Ebook) Modern Multithreading: Implementing, Testing, and Debugging Multithreaded Java and C++/Pthreads/Win32 by Richard H. Carver, Kuo-Chung Tai ISBN 9780471725046, 0471725048 download
(Ebook) Modern Multithreading: Implementing, Testing, and Debugging Multithreaded Java and C++/Pthreads/Win32 by Richard H. Carver, Kuo-Chung Tai ISBN 9780471725046, 0471725048 download
https://ebooknice.com/product/modern-multithreading-implementing-
testing-and-debugging-multithreaded-java-and-c-pthreads-win32-974114
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374
https://ebooknice.com/product/sat-ii-success-math-1c-and-2c-2002-peterson-
s-sat-ii-success-1722018
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312
(Ebook) Master SAT II Math 1c and 2c 4th ed (Arco Master the SAT
Subject Test: Math Levels 1 & 2) by Arco ISBN 9780768923049,
0768923042
https://ebooknice.com/product/master-sat-ii-math-1c-and-2c-4th-ed-arco-
master-the-sat-subject-test-math-levels-1-2-2326094
(Ebook) Cambridge IGCSE and O Level History Workbook 2C - Depth
Study: the United States, 1919-41 2nd Edition by Benjamin
Harrison ISBN 9781398375147, 9781398375048, 1398375144,
1398375047
https://ebooknice.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-53538044
https://ebooknice.com/product/smart-grammar-and-vocabulary-split-
edition-2b-student-s-book-23340516
https://ebooknice.com/product/primary-mathematics-workbook-2b-23520620
https://ebooknice.com/product/primary-mathematics-textbook-2b-23519854
MODERN MULTITHREADING
Implementing, Testing, and
Debugging Multithreaded Java and
C++/Pthreads/Win32 Programs
RICHARD H. CARVER
KUO-CHUNG TAI
RICHARD H. CARVER
KUO-CHUNG TAI
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, scanning, or otherwise,
except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without
either the prior written permission of the Publisher, or authorization through payment of the
appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers,
MA 01923, (978) 750-8400, fax (978) 750-4470, or on the web at www.copyright.com. Requests
to the Publisher for permission should be addressed to the Permissions Department, John Wiley &
Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at
http://www.wiley.com/go/permission.
Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best
efforts in preparing this book, they make no representations or warranties with respect to the
accuracy or completeness of the contents of this book and specifically disclaim any implied
warranties of merchantability or fitness for a particular purpose. No warranty may be created or
extended by sales representatives or written sales materials. The advice and strategies contained
herein may not be suitable for your situation. You should consult with a professional where
appropriate. Neither the publisher nor author shall be liable for any loss of profit or any other
commercial damages, including but not limited to special, incidental, consequential, or other
damages.
For general information on our other products and services or for technical support, please contact
our Customer Care Department within the United States at (800) 762-2974, outside the United
States at (317) 572-3993 or fax (317) 572-4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print
may not be available in electronic formats. For more information about Wiley products, visit our
web site at www.wiley.com.
QA76.642.C38 2006
005.1 1–dc22
2005045775
10 9 8 7 6 5 4 3 2 1
CONTENTS
Preface xi
v
vi CONTENTS
4 Monitors 177
4.1 Definition of Monitors, 178
4.1.1 Mutual Exclusion, 178
4.1.2 Condition Variables and SC Signaling, 178
4.2 Monitor-Based Solutions to Concurrent Programming
Problems, 182
4.2.1 Simulating Counting Semaphores, 182
4.2.2 Simulating Binary Semaphores, 183
4.2.3 Dining Philosophers, 183
4.2.4 Readers and Writers, 187
viii CONTENTS
Index 457
PREFACE
Classroom Use
In our experience, students have a hard time learning to write concurrent pro-
grams. If they manage to get their programs to run, they usually encounter
deadlocks and other intermittent failures, and soon discover how difficult it is to
reproduce the failures and locate the cause of the problem. Essentially, they have
no way to check the correctness of their programs, which interferes with learn-
ing. Instructors face the same problem when grading multithreaded programs. It
xi
xii PREFACE
We have made an effort to minimize the differences between our Java and C++
programs. We use object-oriented features that are common to both languages,
and the class library has been implemented in both languages. Although we don’t
illustrate every example in both Java and C++, the differences are very minor
and it is easy to translate program examples from one language to the other.
Content
The book has seven chapters. Chapter 1 defines operating systems terms such
as process, thread, and context switch. It then shows how to create threads, first
in Java and then in C++ using both the POSIX Pthreads library and the Win32
API. A C++ Thread class is provided to hide the details of thread creation
in Pthreads/Win32. C++ programs that use the Thread class look remarkably
similar to multithreaded Java programs. Fundamental concepts, such as atomicity
and nondeterminism, are described using simple program examples. Chapter 1
ends by listing the issues and problems that arise when testing and debugging
multithreaded programs. To illustrate the interesting things to come, we present
a simple multithreaded C++ program that is capable of tracing and replaying its
own executions.
Chapter 2 introduces concurrent programming by describing various solutions
to the critical section problem. This problem is easy to understand but hard
PREFACE xiii
Online Resources
The home page for this book is located at
http://www.cs.gmu.edu/∼rcarver/ModernMultithreading
This Web site contains the source code for all the listings in the text and for the
synchronization libraries. It also contains startup files and test cases for some of
the exercises. Solutions to the exercises are available for instructors, as is a copy
of our lecture notes. There will also be an errata page.
Acknowledgments
The suggestions we received from the anonymous reviewers were very help-
ful. The National Science Foundation supported our research through grants
CCR-8907807, CCR-9320992, CCR-9309043, and CCR-9804112. We thank our
research assistants and the students in our courses at North Carolina State and
George Mason University for helping us solve many interesting problems. We
also thank Professor Jeff Lei at the University of Texas at Arlington for using
early versions of this book in his courses.
My friend, colleague, and coauthor Professor K. C. Tai passed away before
we could complete this book. K.C. was an outstanding teacher, a world-class
researcher in the areas of software engineering, concurrent systems, programming
languages, and compiler construction, and an impeccable and highly respected
professional. If the reader finds this book helpful, it is a tribute to K.C.’s many
contributions. Certainly, K.C. would have fixed the faults that I failed to find.
RICHARD H. CARVER
Fairfax, Virginia
July 2005
[email protected]
1
INTRODUCTION TO CONCURRENT
PROGRAMMING
1
2 INTRODUCTION TO CONCURRENT PROGRAMMING
are created for system programs. A user process has its own logical address space,
separate from the space of other user processes and separate from the space (called
the kernel space) of the system processes. This means that two processes may
reference the same logical address, but this address will be mapped to different
physical memory locations. Thus, processes do not share memory unless they
make special arrangements with the operating system to do so.
Multiprocessing operating systems enable several programs to execute simul-
taneously. The operating system is responsible for allocating the computer’s
resources among competing processes. These shared resources include memory,
peripheral devices such as printers, and the CPU(s). The goal of a multiprocess-
ing operating system is to have some process executing at all times in order to
maximize CPU utilization.
Within a process, program execution entails initializing and maintaining a
great deal of information [Anderson et al. 1989]. For instance:
given moment, multiple processes, each containing one or more threads, may be
executing. However, some threads may not be ready for execution. For example,
some threads may be waiting for an I/O request to complete. The scheduling
policy determines which of the ready threads is selected for execution.
In general, each ready thread receives a time slice (called a quantum) of
the CPU. If a thread decides to wait for something, it relinquishes the CPU
voluntarily. Otherwise, when a hardware timer determines that a running thread’s
quantum has completed, an interrupt occurs and the thread is preempted to allow
another ready thread to run. If there are multiple CPUs, multiple threads can
execute at the same time. On a computer with a single CPU, threads have the
appearance of executing simultaneously, although they actually take turns running
and they may not receive equal time. Hence, some threads may appear to run at
a faster rate than others.
The scheduling policy may also consider a thread’s priority and the type of
processing that the thread performs, giving some threads preference over others.
We assume that the scheduling policy is fair, which means that every ready thread
eventually gets a chance to execute. A concurrent program’s correctness should
not depend on its threads being scheduled in a certain order.
Switching the CPU from one process or thread to another, known as a context
switch, requires saving the state of the old process or thread and loading the state
of the new one. Since there may be several hundred context switches per second,
context switches can potentially add significant overhead to an execution.
Multithreading allows a process to overlap I/O and computation. One thread can
execute while another thread is waiting for an I/O operation to complete. Mul-
tithreading makes a GUI (graphical user interface) more responsive. The thread
that handles GUI events, such as mouse clicks and button presses, can create
additional threads to perform long-running tasks in response to the events. This
allows the event handler thread to respond to more GUI events. Multithread-
ing can speed up performance through parallelism. A program that makes full
use of two processors may run in close to half the time. However, this level of
speedup usually cannot be obtained, due to the communication overhead required
for coordinating the threads (see Exercise 1.11).
Multithreading has some advantages over multiple processes. Threads require
less overhead to manage than processes, and intraprocess thread communication
is less expensive than interprocess communication. Multiprocess concurrent pro-
grams do have one advantage: Each process can execute on a different machine
(in which case, each process is often a multithreaded program). This type of
concurrent program is called a distributed program. Examples of distributed pro-
grams are file servers (e.g., NFS), file transfer clients and servers (e.g., FTP),
remote log-in clients and servers (e.g., Telnet), groupware programs, and Web
browsers and servers. The main disadvantage of concurrent programs is that they
4 INTRODUCTION TO CONCURRENT PROGRAMMING
are extremely difficult to develop. Concurrent programs often contain bugs that
are notoriously difficult to find and fix. Once we have examined several concur-
rent programs, we’ll take a closer look at the special problems that arise when
we test and debug them.
A Java program has a main thread that executes the main() function. In addi-
tion, several system threads are started automatically whenever a Java program
is executed. Thus, every Java program is a concurrent program, although the
programmer may not be aware that multiple threads are running. Java provides
a Thread class for defining user threads. One way to define a thread is to define
a class that extends (i.e., inherits from) the Thread class. Class simpleThread in
Listing 1.1 extends class Thread. Method run() contains the code that will be exe-
cuted when a simpleThread is started. The default run() method inherited from
class Thread is empty, so a new run() method must be defined in simpleThread
in order for the thread to do something useful.
The main thread creates simpleThreads named thread1 and thread2 and
starts them. (These threads continue to run after the main thread completes its
statements.) Threads thread1 and thread2 each display a simple message and
terminate. The integer IDs passed as arguments to the simpleThread constructor
are used to distinguish between the two instances of simpleThread.
A second way to define a user thread in Java is to use the Runnable interface.
Class simpleRunnable in Listing 1.2 implements the Runnable interface, which
means that simpleRunnable must provide an implementation of method run().
The main method creates a Runnable instance r of class simpleRunnable, passes
r as an argument to the Thread class constructor for thread3, and starts thread3.
Using a Runnable object to define the run() method offers one advantage
over extending class Thread. Since class simpleRunnable implements interface
Runnable, it is not required to extend class Thread, which means that
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com