img
.
Chapter 12. Design
Making Libraries Safe and Hot
Manipulating Lists
Program Design
Design Patterns
Making Libraries Safe and Hot
Now that we've discussed the grand generalities of what is possible, let's move to the other
extreme and take a look at some of the specific programming issues that MT programs come up
against and how they can be dealt with. We'll look at the issues of designing and working with
libraries--the vendor's libraries, third-party libraries, and your own libraries--how they can be
written to be both correct and efficient. By far the most important design issue is simplicity.
Debugging multithreaded programs is difficult and the current tools are not that good (because
none of us have figured out how to build better tools!), so this is a major issue.
Often, there are simple, obvious methods of making functions MT-safe. Sometimes these methods
work perfectly, but sometimes they introduce contention between different threads calling those
functions. The job of the library writer is to analyze those situations and make things fast.
We're going to look first at some functions in C because (1) these are good examples of the issues
involved, (2) they are real examples from productions systems, and (3) we had this section left
over from the last topic and wanted to use it. We can divide functions into a number of categories.
Trivial Library Functions
Many functions are trivially safe. Functions like sin() have no need to write any shared data and
can be used exactly as first implemented thirty years ago.
Another set of functions has very little shared state and can be made thread-safe simply by
surrounding the use of global data with a lock. The pseudo-random number generator, rand(), is
a very small, fast function that takes about 1 s on an SS10/40. It uses a seed value that it changes
on each call. By protecting that seed, the function can be made safe (Code Example 12-1). This
new version of rand() is safe and now runs about 1 s slower due to the mutex. For most
programs, this is fine.
Example 12-1 Simple MT-Safe Implementation of rand(), Version 1
rand_1() {
static unsigned int seed;
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
int value;
pthread_mutex_lock(&m);
value = _rand(&seed);
/* Calculate new value, update seed */
pthread_mutex_unlock(&m);
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home