OSF DCE Application Development Guide--Core Components

Chapter 10. DCE Threads Example
The example in this chapter shows the use of DCE Threads in a C program that performs
a prime number search. The program finds a specified number of prime numbers, then
sorts and displays these numbers. Several threads participate in the search: each thread
takes a number (the next one to be checked), sees if it is a prime, records it if it is prime,
and then takes another number, and so on.
This program shows the work crew model of programming (see Chapter 6). The workers
(threads) increment a number (current_num) to get their next work assignment, which
in this case is the same task as before, but with a different number to check for a prime.
As a whole, the worker threads are responsible for finding a specified number of prime
numbers, at which point their work is completed.
10.1 Details of Program Logic and Implementation
The number of workers to be used and the requested number of prime numbers to be
found are defined constants. A macro is used to check for bad status (bad status returns a
value of -1), and to print a given string and the associated error value upon bad status.
Data to be accessed by all threads (mutexes, condition variables, and so forth) are
declared as global items.
Worker threads execute the prime search routine, which begins by synchronizing with
the boss (or parent) thread by using a predicate and a condition variable. Always enclose
a condition wait in a predicate loop to prevent a thread from continuing if it receives a
spurious wakeup. The lock associated with the condition variable must be held by the
thread when the condition wait call is made. The lock is implicitly released within the
condition wait call and acquired again when the thread resumes. The same mutex must
be used for all operations performed on a specific condition variable.
After the parent sets the predicate and broadcasts, the workers begin finding prime
numbers until canceled by a fellow worker who has found the last requested prime
number. Upon each iteration, the workers increment the current number to be worked on
and take the new value as their work item. A mutex is locked and unlocked around
getting the next work item. The purpose of the mutex is to ensure the atomicity of this
operation and the visibility of the new value across all threads. This type of locking
124245 Tandem Computers Incorporated 101