OSF DCE Application Development Guide--Introduction and Style Guide

Chapter 2. Threads
Threads as used specifically in DCE applications raise several obvious policy issues
which may be summarized, roughly, as follows:
When to use multiple threads
How many threads to use
What scheduling and priority attributes to apply
These issues are covered in Section 2.1.
Beyond these obvious policy questions, however, threads raise a tricky issue for a
programming policy guide because it is not always clear where the line between
mechanism and policy lies. Multithreaded programming in general requires a number of
practices that are likely to be unfamiliar and unintuitive to many programmers, and errors
arising from failure to follow these practices can be obscure, infrequent, and difficult to
reproduce. One result is that an incorrect program can easily appear to be correct.
A typical case is a program that performs the following sequence of steps:
pthread_create(&thread...);
pthread_setprio(thread...);
From the point of view of a single thread, this may seem like a logical sequence of steps,
yet it contains a fundamental error: the spawned thread may well have begun to execute,
or even have terminated, by the time the call to pthread_setprio( ) occurs. The result is
a program whose behavior is indeterminate, and which may fail unpredictably. The
correct procedure is to use a thread attributes object to set the thread’s priority when it is
created.
Strictly speaking, this is really a programming mechanism issue, since the failure to
follow the rule results in an incorrect program. However, errors of this type can be
obscure: in fact, the resulting program might never fail due to this error. There are many
such error possibilities in a multithreaded program that can result in all kinds of
deadlocks, race conditions, and data corruption. Yet these errors can sometimes be so
obscure as to be extremely difficult to analyze a priori, and failures may occur so rarely
as to be virtually unreproducible.
As a result, correct use of threads mechanisms requires following a set of general rules
designed to avoid errors that may or may not occur in specific cases. For example, locks
124246 Tandem Computers Incorporated 21