Tru64 UNIX

Tru64 UNIX

Guide to the POSIX Threads Library

Order Number: AA--RH9RC--TE


April 2000

This guide reviews the principles of multithreaded programming, as reflected in the IEEE® POSIX® 1003.1-1996 standard, and provides implementation guidelines and reference information for the HP Multithreading Run-Time Library.

Revision/Update Information: This guide supersedes the Guide to DECthreads, printed July 1999.

Product Version: Tru64 UNIX Version 5.0A or higher





Hewlett-Packard Company Palo Alto, California


© 2002 Hewlett-Packard Company

Microsoft® is a trademark of Microsoft Corporation in the U.S. and/or other countries. The Open Group tm, UNIX®, and X/Open® are trademarks of The Open Group in the U.S. and/or other countries. All other product names mentioned herein may be the trademarks of their respective companies.

Confidential computer software. Valid license from Compaq Computer Corporation, a wholly owned subsidiary of Hewlett-Packard Company, required for possession, use, or copying. Consistent with FAR 12.211 and 12.212, Commercial Computer Software, Computer Software Documentation, and Technical Data for Commercial Items are licensed to the U.S. Government under vendor's standard commercial license.

None of Compaq, HP or any of their subsidiaries shall be liable for technical or editorial errors or omissions contained herein. The information is provided "as is" without warranty of any kind and is subject to change without notice. The warranties for HP or Compaq products are set forth in the express limited warrant statements accompanying such products. Nothing herein should be construed as constituting an additional warranty.

This document is available on CD-ROM.

Contents Index


Preface

This guide describes the POSIX Threads Library, the HP Multithreading Run-Time Library. In addition to introducing components for building multithreaded applications and libraries to be called from either single-threaded or multithreaded programs, this guide reviews the key principles of multithreaded programming.

This guide also presents the concepts behind thread-safe and multithreaded processing environments and provides guidelines for using the library to implement them on various HP and Compaq platforms. Finally, this guide describes in detail each routine in the two recommended interfaces:

The interface you select depends upon your goals and the anticipated environment for your software.

As a complement to this guide, and for a user's guide to multithreaded programming using the pthreads standard, we recommend the following:

Programming with POSIX Threads by David R. Butenhof, published as part of the Addison-Wesley Professional Computing Series (ISBN 0-201-63392-2).
The Single UNIX Specification, Version 2, The Open Group (ISBN 85912-181-0). Available online at http://www.opengroup.org/onlinepubs/7908799/toc.htm.

Intended Audience

This guide is for system and application programmers who use the POSIX Threads Library either to create multithreaded applications or to create thread-safe code libraries that can be called from either single-threaded or multithreaded applications.

Document Structure

This guide consists of the following:

Part 1

Part 2

Part 3

Part 4 - Appendixes

Glossary

Related Documents

See your system's documentation set for more information on that system. This manual covers the version of the POSIX Threads Library available on the following platforms:

The printed version of the Tru64 UNIX documentation set uses letter icons on the spines of the books to help specific audiences quickly find the books that meet their needs. (You can order the specific books from HP.) The following list describes this convention:
Icon Audience
G General users
S System and network administrators
P Programmers
D Device driver writers
R Reference page users

Some books in the OpenVMS or Tru64 UNIX documentation set help meet the needs of several audiences. For example, the information in some system manager, system administrator, or user books is also used by programmers. Keep this in mind when searching for information on specific topics. The New Features Manual provides information on all of the books in the OpenVMS or Tru64 UNIX documentation set.

Reader's Comments

HP welcomes your comments on this or any other guide. You can send comments as follows:

Please include the following information along with your comments:

Note: Please address technical questions to your local system vendor or to the appropriate HP technical support office. Information provided with this software media explains how to send problem reports to HP.

Conventions

Table 1 shows the conventions used in this manual.

Table 1 Conventions
Convention Description
%
$
A percent sign represents the C shell system prompt. A dollar sign represents the system prompt for the Bourne and Korn shells. It is also the default OpenVMS prompt.
# A number sign represents the superuser prompt.
cat(1) A cross-reference to a UNIX reference page includes the appropriate section number in parentheses. For example, cat(1) indicates that you can find information on the cat command in Section 1 of the UNIX Programmer reference pages.
Ctrl/ x The key combination Ctrl/ x indicates that you must press the key labeled Ctrl while you simultaneously press another key, for example, Ctrl/Y or Ctrl/Z.
monospaced text This typeface indicates the name of a command, routine, service, exception, or file. This typeface is also used in interactive examples and other screen displays.
monospaced text This bolded typeface represents user input in interactive examples in the hardcopy and online versions of this guide.
... A horizontal ellipsis in a figure or example indicates that not all of the statements are shown.
.
.
.
A vertical ellipsis indicates the omission of items from a code example or command format; the items are omitted because they are not important to the topic being discussed.
() In format descriptions, parentheses indicate that, if you choose more than one option, you must enclose the choices in parentheses.
[] In format descriptions, brackets indicate that whatever is enclosed is optional; you can select none, one, or all of the choices.
{} In format descriptions, braces surround a required choice of options; you must choose one of the options listed.
boldface text Boldface text represents the introduction of a new term.
italic text Italic text represents book titles, parameters, arguments, and information that can vary in system messages (for example, Internal error number).
numbers Unless otherwise noted, all numbers in the text are assumed to be decimal. Nondecimal radixes---binary, octal, or hexadecimal---are explicitly indicated.
mouse The term mouse refers to any pointing device, such as a mouse, a puck, or a stylus.


Part 1
POSIX Threads Library Overview and Programming Guidelines

Part 1 contains chapters that provide an overview and concepts of the Threads Library as well as define programming disciplines and guidelines for writing a multithreaded program.


Chapter 1
Introducing Multithreaded Programming

This chapter introduces the concepts of threads and multithreaded programming. It describes four functional models that can be a basis for constructing multithreaded applications. The concepts and techniques introduced here are described in more detail in Chapter 2 and in this guide's platform-specific appendixes.

This chapter's last section introduces the components of the POSIX Threads Library package, in particular the pthread and tis interfaces, and how those components support building multithreaded applications and thread-safe libraries.

1.1 Advantages of Using Threads

Multithreaded programming means organizing and coding a program so that instances of its routines, called threads, can execute concurrently in the same process. You use threads to improve a program's performance---that is, its throughput, computational speed, responsiveness, or some combination.

Using threads can improve a program's performance on uniprocessor systems by permitting the overlap of input, output, or other slow operations with computational operations. Threads are useful in driving slow devices such as disks, networks, terminals, and printers. A multithreaded program can perform other useful work while waiting for the device to produce its next event, such as the completion of a disk transfer or the receipt of a packet from the network.

Using threads can also be advantageous when constructing an application's user interface. Consider the typical arrangement of a window system. Each time the user invokes an action (for example, by clicking on a mouse button), the program can use a separate thread to implement the action. If the user invokes multiple actions, multiple threads can perform the actions in parallel.

Using threads is especially advantageous when building a distributed system. These systems frequently contain a shared network server, where the server services requests from multiple clients. Using multiple threads allows the server to handle clients' requests in parallel, instead of artificially serializing them or creating (at great expense) one server process per client.

A program with multiple threads can be especially suited to run on a multiprocessor system, where threads run concurrently on separate processors. Threads created using the POSIX Threads Library are capable of utilizing multiprocessors, if the target platform supports parallelism within a process. The HP Tru64 UNIX platforms and OpenVMS Alpha platforms support parallelism; the OpenVMS VAX platform does not support parallelism.

1.2 Overview of Threads

A thread is a single, sequential flow of control within a process. Within each thread there is a single point of execution. Most traditional programs execute as a process with a single thread. Figure 1-1 and Figure 1-2 show the differences between a single-threaded process and a multithreaded process.

Figure 1-1 Single-Threaded Process


In Figure 1-2, notice that multiple threads share heap storage, static storage, and code but that each thread has its own register set and stack.

Using the HP multithreading run-time library, a programmer can create several threads within a process. The process' threads execute concurrently. Within a multithreaded program there are at any time multiple points of execution.

Threads execute within (and share) a single address space; therefore, a process' threads can read and write the same memory locations. When the threads access the same memory locations, your program must use synchronization elements, such as mutexes and condition variables, to ensure that the shared memory is accessed correctly. The Threads Library provides routines that allow you to use these and other synchronization objects. Section 2.4 describes the synchronization objects that the Threads Library offers as well as the operations your program can perform on them.

Figure 1-2 Multithreaded Process


1.3 Thread Execution

You should design and code a multithreaded program with the assumption that its threads execute simultaneously. That is, your program cannot make assumptions about the relative start or finish times of its threads or the sequence in which they execute. These are governed by the thread scheduler, part of the run-time environment that the Threads Library establishes before your program begins running. Nevertheless, your program can influence how threads are scheduled by setting each thread's scheduling policy and scheduling priority. ( Section 2.3.6 describes how thread scheduling works.)

Each thread has its own thread identifier, which distinguishes it from all other threads in the process. In addition to the thread's scheduling policy and scheduling priority, each thread is associated with any thread-specific instances of data objects and with thread-specific system resources to support a flow of control.

A thread changes its state over the course of its execution. A thread is in one of the following states:

Figure 1-3 shows the transitions between states for a typical thread implementation.

Figure 1-3 Thread State Transitions


1.4 Functional Models for Multithreaded Programming

The following sections describe four functional models of processing information that are especially well suited for implementation in multithreaded programs:

1.4.1 Boss/Worker Model

In a boss/worker model, one thread functions as the "boss" because it assigns tasks for "worker" threads to perform. Each worker performs a distinct task until it has finished, at which point it notifies the boss that it is ready to receive another task. Alternatively, the boss polls workers periodically to see whether any is ready to receive another task.

A variation of the boss/worker model is the work queue model. The boss places tasks in a queue, and workers check the queue and take tasks to perform. When there are multiple bosses, this is often called producer/consumer.

An example of the work queue model in an office environment is a secretarial typing pool. The office manager boss puts documents to be typed in a basket, and worker typists take documents from the basket to work on.

1.4.2 Work Crew Model

In the work crew model, multiple threads work together on a single task. The task is divided into pieces that are performed in parallel, and each thread performs one piece.

An example of a work crew is a group of people cleaning a building. Each person cleans certain rooms or performs certain types of work (washing floors, polishing furniture, and so forth), and each works independently.

In a multithreaded program that reflects the work crew model, each thread executes a task that can be performed in parallel. Figure 1-4 shows a task performed by three threads in a work crew model.

Figure 1-4 Work Crew Model of Thread Operation


1.4.3 Pipelining Model

In the pipelining model, a task is divided into steps. The steps must be performed in sequence to produce a single instance of the desired result, and the work done in each step (except for the first and last) is based on the previous step and is a prerequisite for the work in the next step. However, the goal is to produce multiple instances of the desired result, and the steps are designed to operate in parallel: while one step is performed on one instance of the result, the preceding step can be performed on the next instance of the result.

An example of the pipelining model is an automobile assembly line. Each step or stage in the assembly line is continually busy receiving the product of the previous stage's work, performing its assigned work, and passing the product along to the next stage.

In a multithreaded program that reflects the pipelining model, each thread executes a step in the task. Figure 1-5 shows a task performed by three threads in a pipelining model.

Figure 1-5 Pipelining Model of Thread Operation


1.4.4 Combination of Functional Models

If the task that your program performs is complex, you might find it appropriate to organize it as a combination of the functional models previously described. For example, a program could follow the pipelining model, but with one or more steps performed by a set of threads that follow a work crew model. In addition, threads could be assigned to a work crew by taking a task from a work queue and deciding (based on the task characteristics) which threads are needed for the work crew.


Next Contents Index