Home > Store

Threads Primer: A Guide to Multithreaded Programming

Register your product to gain access to bonus material or receive a coupon.

Threads Primer: A Guide to Multithreaded Programming

Book

  • Sorry, this book is no longer in print.
Not for Sale

About

Features

  • describes the design of the Solaris MT API, with references to distinctions in POSIX.
  • contains a set of example programs which illustrate the usage of the Solaris and POSIX APIs.
  • explains the use of programming tools: Thread Analyzer, LockLint, LoopTool, and Debugger.

Description

  • Copyright 1996
  • Dimensions: 7 x 9 1/4
  • Pages: 352
  • Edition: 1st
  • Book
  • ISBN-10: 0-13-443698-9
  • ISBN-13: 978-0-13-443698-2

Providing an overview of the Solaris and POSIX multithreading architectures, this book explains threads at a level that is completely accessible to programmers and system architects with no previous knowledge of threads. KEY TOPICS: Covers the business and technical benefits of threaded programs, along with discussions of third party software that is threaded, pointing out the benefits. MARKET: For programmers, system architects, and technical programmer managers.

Sample Content

Table of Contents



Acknowledgments.


Preface.


1. Introduction.


2. Concepts.

Background: Traditional Operating Systems. What Is a Thread? Kernel Interaction. System Calls. Signals. Synchronization. Scheduling. The Value of Using Threads. Parallelism. Throughput. Responsiveness. Communications. System Resources. Distributed Objects. Same Binary for Uniprocessors and Multiprocessors. Program Structure. Single Source for Multiple Platforms. What Kind of Programs to Thread? Inherently MT Programs. Not Obviously MT Programs. Automatic Threading. Programs Not to Thread. What About Shared Memory? Threads Standards. Performance. Solaris 2. NFS. SPECfp. PAR93. Dakota Scientific Software, Inc.. MARC Analysis Inc.. Delphax and Uniq Inc. Adobe. Facet Decision Systems, Inc.. The ImagiNation Network. Visual Numerics. Vantage Analysis Systems, A Viewlogic Company. Landmark Graphics. University of Houston. Geophysical Development Corporation. InfoGraphix. Technologies Incorporated. Scitex. Western Geographical.



3. Foundations.

Implementation vs. Specification. Thread Libraries. The Process Structure. Lightweight Processes. Threads and LWPs. Solaris Multithreaded Model. System Calls. Signals. Don't Use Signal Handlers! Per-Thread Timers.



4. Scheduling.

Different Models of Kernel Scheduling. Threads Are Not Always User- level Entities. Thread Scheduling. Thread Scheduling Details. Context Switching. Preemption. How Many LWPs? Bound Threads and Real-time LWPs. Binding LWPs to Processors. When Should You Care About Scheduling? Thread Creation and Destruction. Returning Status and Memory. That's Not a Bug, That's a Feature! Exiting the Process. Cancellation.



5. Synchronization.

Synchronization Issues. Memory Model. Critical Sections. Lock Your Global Variables! Synchronization Variables. Mutexes. Reader/Writer Locks. Condition Variables. Semaphores. Barriers. Event Semaphores. OS/2 Critical Sections. Spin Locks. Adaptive Locks. Cross-process Synchronization Variables. Synchronization Variable Initialization and Destruction. Synchronization Problems. Deadlocks. Race Conditions. Recovering from Deadlocks. Priority Inversion. FIFO Mutexes. Thread-specific Data. Thread Local Storage. Global Variables, Constants, and Cheating. Comparing the Four Libraries.



6. Operating System Issues.

The Solaris Threads Library. Solaris Multithreaded Kernel. Concurrency vs. Parallelism. Solaris Symmetric Multiprocessing. Kernel Scheduling. Are Libraries Safe? Async Safety. New Semantics for System Calls. Forking New Processes. Executing a New Program. The New System Call sigwait(2). The Solaris Operating Environment. SVR4 and SPEC 1170 Compliant. Real-Time, Fully Preemptable Kernel. SMP. Dynamically Loadable Kernel Modules. Auto-Configuration. Dynamically Loadable, Shared Memory Modules. Memory-Mapped Files. Optimized Swap Space. Transport-Layer Interfaces. Cache File System and Auto File System. Interactive Scheduling Class. In-kernel rlogin/telnet. Wabi and MAE. Network Information Service Plus. CDE. Project DOE. Multiple Hardware Architectures. Solaris Threads Debugging Interface. Comparisons of Different Implementations.



7. POSIX Threads (pthreads).

Pthreads Introduction. Attribute Objects. Threads and Attribute Objects. Synchronization Variables and Attribute Objects. Cancellation. Thread Scheduling. Moving Between the Two APIs.



8. Programming Tools.

LockLint. LoopTool. SPARCworks Debugger. Thread Analyzer. Examples of Using the Tools. Example One: Threading the Mandelbrot Program. Example Two: Checking a Program with LockLint. Example Three: Parallelizing Loops with LoopTool. Example Four: Using the SPARCworks Debugger. For More Information.



9. Programming With Threads.

Global Variables (errno). Static Local Variables. Synchronizing Threads. Single-Lock Strategy. Reentrance. Avoiding Deadlock. Scheduling Problems. Locking Guidelines. Following Some Basic Guidelines. Creating Threads. Thread Concurrency. Bound Threads.



10. Examples.

Using thr_create() and thr_join(). Producer/Consumer. Matrix Multiplication. Threads and Windows. Socket Server. Using Many Threads. Real- time Thread. POSIX Cancellation. Deadlock. Software Race Condition. Signal Handler. Interprocess Synchronization. Arrays.



Appendices.

A. Answers. B. Solaris Signal Implementation. C. Threads on the Net. Threads on the World Wide Web. The SPILT Package for Solaris/POSIX Compatibility. Threads Newsgroup. Code Examples. The Authors on the Net. D. Timings. E. Common Bugs. Failure to Check Return Values for Errors. Using errno Without Checking the Return Value. Not Joining on Nondetached Threads. Failure to Verify that Library Calls Are MT Safe. Insufficient Swap Space. Creating Excessive LWPs. Forgetting to Include the -D_REENTRANT Flag. Using Spin Locks. Depending upon Scheduling Order. Using errno for Threads Library Functions. Not Recognizing Shared Data. F. Compile and Debug Specifics. Compiling a Multithreaded Application. Using libthread. Debugging Multithreaded Programs. Using adb. Using dbx. G. Application Program Interface. Condition Functions. Mutex Functions. Reader/Writer Lock Functions. Semaphore Functions. Thread Functions. H. Pthreads API (POSIX 1003.1c). Condition Functions. Condition Attribute Functions. Mutex Functions. Mutex Attribute Functions. Pthread Functions. Pthread Attribute Functions. Semaphore Functions.



Glossary.


Index.

Preface

Today, there are three primary sets of multithreading (MT) libraries: the "standards-based" libraries (all of the UNIX® implementations, which will move to POSIX upon ratification), the OS/2® library, and the Windows NT(TM) library.

(The NT and OS/2 libraries are fairly similar, which should not be too surprising. NT did start life as OS/2, version 2, after all.) Although the APIs and implementations differ significantly, the fundamental concepts are the same. The ideas in this book are valid for all three; the details of the APIs differ.

All the specific discussion in this book focuses on the Solaris(TM) 2 and POSIX multithreading models, with comparisons to OS/2 and NT throughout. We concentrate on the Solaris implementation in greatest detail. We do so because the Solaris threads library is currently the most advanced and robust implementation available, has the maximum exposure, the best thread-aware tool suite, and conforms most closely to the POSIX standard. (The fact that we both work for Sun has nothing to do with it.)

A frank note about our motivation is in order here. We have slaved away for countless hours on this book because we're propeller-heads who honestly believe that this technology is a superb thing and that the widespread use of it will make the world a better place for hackers like ourselves. Sun's motivation for assisting us in the project is to promote the usage of MT, because (a) this means you can write better, faster programs on Solaris, increasing sales of the operating system, and (b) Sun is far ahead of everybody else in both MT and multiprocessor (MP) machines, so it should leverage hardware sales, too.

Your motivations for writing MT programs? You can write your programs better and more easily, they'll run faster, and you'll get them to market more quickly, they'll have fewer bugs, you'll have happier programmers, customers, and higher sales. The only losers in this game are the competitors, who lag behind Sun in MP hardware and MT software and will lag behind you in application speed and quality.

MT is here today. It will soon be ubiquitous. As a professional programmer, you have an obligation to understand this technology. It may or may not be appropriate for your current project, but you must be able to make that conclusion yourself. This book will give you what you need to make that decision.

Welcome to the world of the future!

Who Should Use This Book

This book aims to give the programmer or technical manager a solid, basic understanding of threads-what they are, how they work, why they are useful, and some of the programming issues surrounding their use. As an introductory text, it does not attempt a deep, detailed analysis. After reading this book you should have a solid understanding of the fundamentals, be able to write credible, modestly complex, threaded programs and have the understanding necessary to analyze your own programs and determine the viability of threading them.

This book is written with the experienced C/UNIX programmer in mind. A non-UNIX programmer will find a few of the details unfamiliar, but the concepts clear.

A non-C programmer will find the code fragments and API descriptions mildly challenging, though possible to decipher, while the concepts should be clear. A technically minded nonprogrammer should be able to follow most of the concepts and understand the value of threads. A nontechnical person will not get much from this book.

How This Book Is Organized

Chapter 1, Introduction - In which we present the motivation for creating thread libraries, discuss the advent of shared memory multiprocessors, and the interactions between threads and SMP machines.

Chapter 2, Concepts - In which the reader is introduced to the basic concepts of multitasking operating systems and of multithreading as it compares to other programming paradigms. The reader is shown a set of reasons why multithreading is a valuable addition to programming paradigms, and a number of examples of successful deployment are presented.

Chapter 3, Foundations - In which the reader is introduced to the underlying structures upon which threads are built, the construction of the thread itself, and the operating system support that allows an efficient implementation.

Chapter 4, Scheduling - In which we explain the myriad details of the different scheduling models. After the reader is given a firm grounding in the fundamental concepts, we explain the various alternative choices that could have been made. Finally, the reader is treated to a comprehensive explanation of the intricacies in the life of a thread.

Chapter 5, Synchronization - In which the reader is led on a hunt for the intimidating synchronization variables and discovers that they are not actually as frightening as had been thought. After the hardware and software issues surrounding them are explained, the reader is shown the trade-offs involved in selecting the proper one to use. The chapter concludes with an explanation of thread-specific data.

Chapter 6, Operating System Issues - In which we explore a variety of operating systems issues that bear heavily upon the usability of the threads library in actual programs. We also examine a set of general operating system functions and their value.

Chapter 7, POSIX Threads (pthreads) - In which the details of the POSIX concepts are explained and contrasted to those of Solaris. A brief consideration of the issues of moving from Solaris threads to POSIX threads concludes the chapter.

Chapter 8, Programming Tools - In which we consider the kinds of new tools that a reader would want when writing an MT program. Details of the Solaris tool set are discussed in the context of working with actual programs.

Chapter 9, Programming With Threads - In which some pointers on programming with threads are given. Differences between single- threaded thinking and multithreaded thinking are emphasized.

Chapter 10, Examples - In which several example programs are presented, and their details and issues surrounding the way they use threads are discussed.

Recommended Reading

As of this writing, there are no other books specifically on the topic of multithreading concepts, although we know that several will be coming out within a year of this publication. Many of the operating system books and programming guides contain listings of the APIs but do not attempt to deal with the concepts of MT.

Related Books

Advanced Windows NT: The Developer's Guide to the Win32 Application Programming Interface. Jeffrey Richter. Microsoft Press, 1994. ISBN 1- 55615-567-0. This book contains about 200 pages that cover the NT threads API and its usage. It covers the API well, contains a good amount of code, but very little theory.

Multithreaded Computer Architecture: A Summary of the State of the Art. Edited by Robert A. Iannucci. Kluwer Academic Publishers, 1994. ISBN 0-7923-9477-1. This book is a collection of papers dealing with hardware design considerations for building specialized machines that can support multithreaded programs.

Programming with Threads. Steve Kleiman, Devang Shah, Bart Smaalders. Sun Microsystems Press/Prentice Hall PTR, Publication date late fall 1995. ISBN 0-13-172389-8. This book will be the definitive guide to developing multithreaded programs on UNIX, going into great depth on theory and practice.

Real-World Programming for OS/2 2.1. Derrel R. Blain, Kurt R. Delimon, Jeff English. Sams Publishing/Prentice Hall PTR, 1993. ISBN 0-672- 30300-0. This book contains about 50 pages that cover the OS/2 threads API and its usage. It covers the API well, contains one nice example but very little theory.

Solaris Multithreaded Programming Guide. Sun Microsystems Press/Prentice Hall PTR, 1995. ISBN 0-13-160896-7. This is the documentation that comes with Solaris and contains all the information about the API. It is also available as part of the Solaris AnswerBook® and via the threads page on the WWW (see Appendix\x11C, Threads on the Net).

Using Multi-C: A Portable Multithreaded C Programming Library. Prentice Hall PTR, 1994. ISBN 0-13-606195-8. This book describes the API and use of the MIX Multi-C library, which is a proprietary library providing similar kinds of functionality to POSIX threads.

Related Papers

There are a number of papers from technical conferences that go into great detail of the different aspects of multithreading. You can find those that we felt were most interesting on the thread's home page. (See Appendix C, Threads on the Net.)

Updates

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020