Guide to DECthreads

Guide to DECthreads

Order Number: AA--Q2DPD--TK


December 1997

This guide reviews the principles of multithreaded programming, as reflected in the IEEE POSIX 1003.1c-1995 standard, and provides implementation guidelines and reference information for DECthreads, Compaq's Multithreading Run-Time Library.

Revision/Update Information: This guide supersedes the Guide to DECthreads, printed March 1996.

Product Version: Tru64 UNIX Version 4.0D

Compaq Computer Corporation

Houston, Texas


December 1997

COMPAQ, the Compaq logo, and the Digital logo are registered in the U.S. Patent and Trademark Office. Alpha, AlphaServer, NonStop, TruCluster, and Tru64 are trademarks of Compaq Computer Corporation.

Microsoft and Windows NT are registered trademarks of Microsoft Corporation. Intel, Pentium, and Intel Inside are registered trademarks of Intel Corporation. UNIX is a registered trademark and The Open Group is a trademark of The Open Group in the United States and other countries. Other product names mentioned herein may be the trademarks of their respective companies.

Possession, use, or copying of the software described in this publication is authorized only pursuant to a valid written license from Compaq Computer Corporation or an authorized sublicensor.

Compaq Computer Corporation shall not be liable for technical or editorial errors or omissions contained herein. The information in this document is subject to change without notice.

ZK6493

(This document is available on CD--ROM.)


Contents


Preface

This guide describes DECthreads, Compaq's Multithreading Run-Time Library. In addition to introducing DECthreads components for building multithreaded applications and libraries to be called from other single-threaded or multithreaded programs, this guide reviews the key principles of multithreaded programming as reflected in the IEEE POSIX 1003.1c-1995 standard.

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

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

As a complement to this guide, and for a user's guide to multithreaded programming using the IEEE POSIX 1003.1c-1995 standard, we recommend:

Intended Audience

This guide is for system and application programmers who use DECthreads to create multithreaded applications or to create thread-safe code libraries that can be called from 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. DECthreads is available on the following platforms:

Compaq has changed the name of its UNIX® operating system from DIGITAL UNIX to Compaq Tru64 UNIX. The new name reflects Compaq's commitment to UNIX and its conformance to UNIX standards.

For a complete list and description of the books in the OpenVMS documentation set, see the Overview of OpenVMS Documentation.

The printed version of the Tru64 UNIX document set is color coded to help specific audiences quickly find the books that meet their needs. This color coding is reinforced with the use of an icon on the spines of books. The following list describes this convention:
Audience Icon Color Code
General users G Blue
System and network administrators S Red
Programmers P Purple
Device driver writers D Orange
Reference page users R Green

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 Documentation Overview, Glossary, and Master Index provides information on all of the books in the OpenVMS or Tru64 UNIX documentation set.

Reader's Comments

Compaq welcomes your comments on this or any other guide. You can send comments in the following ways:

Please include the following information along with your comments:

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

How To Order Additional Documentation

Use the following table to order additional documentation or information. If you need help deciding which documentation best meets your needs, call 800-DIGITAL (800-344-4825).

Conventions

In this guide, every use of OpenVMS means the OpenVMS operating system, and every use of UNIX means the Tru64 UNIX operating system.

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.
# A number sign represents the superuser prompt.
cat(1) A cross-reference to a 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 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
DECthreads Overview and Programming Guidelines

Part 1 contains chapters that provide an overview and concepts of DECthreads as well as defining programming disciplines and guidelines for writing a multithreaded program.


Chapter 1
Introducing DECthreads for 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 DECthreads 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 DECthreads library are capable of utilizing multiprocessors, if the target platform supports parallelism within a process. Compaq's Tru64 UNIX-based 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 DECthreads, Compaq's multithreading run-time library, a programmer can create several threads within a process. The process's 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's 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. DECthreads provides routines that allow you to use these and other synchronization objects. Section 2.4 describes the synchronization objects that DECthreads 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 DECthreads thread scheduler, part of the run-time environment that DECthreads establishes before your program begins running. Nevertheless, your program can influence how DECthreads schedules its threads, 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 thread-common 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



Note

Building your multithreaded program must produce executable code that is reentrant. Therefore, be sure that your compiler generates reentrant code before you design or code your multithreaded program. By default, Compaq's C, C++, Ada, Pascal, and BLISS compilers generate reentrant code.

If you cannot build your program so that its executable code is reentrant, it might be impossible to keep the program's threads from interfering with each other. See Section 3.8.1 for more information about thread-reentrant libraries.

In general, when using threads, be aware of language-based programming practices that are inherently not thread safe. ("Thread safety" is explained in Section 3.8.2.) You must address these factors when writing multithreaded applications and thread-safe libraries. For example, Fortran language routines typically rely heavily upon static storage, which can prevent those routines from being thread safe.


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.

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.

1.5 Potential Issues for Multithreaded Programs

When you design and code a multithreaded program, you must accommodate or eliminate, as appropriate, each of the following issues:

1.6 DECthreads Libraries and Interfaces

As a package, DECthreads is a collection of shared code libraries and C language header files that declare entry points into those libraries. This guide's platform-specific appendixes describe these libraries in more detail and list all other libraries upon which the DECthreads libraries depend.

From the programmer's view the DECthreads libraries offer interfaces. Each interface is a distinct set of routines that together provide a well-defined set of related data objects and operations.

This version of DECthreads supports two interfaces that are documented in this guide:


Next | Contents