JavaScript is required to for searching.
Skip Navigation Links
Exit Print View
Multithreaded Programming Guide     Oracle Solaris 11.1 Information Library
search filter icon
search icon

Document Information

Preface

1.  Covering Multithreading Basics

2.  Basic Threads Programming

3.  Thread Attributes

4.  Programming with Synchronization Objects

5.  Programming With the Oracle Solaris Software

6.  Programming With Oracle Solaris Threads

7.  Safe and Unsafe Interfaces

8.  Compiling and Debugging

9.  Programming Guidelines

Rethinking Global Variables

Providing for Static Local Variables

Synchronizing Threads

Single-Threaded Strategy

Reentrant Function

Code Locking

Data Locking

Invariants and Locks

Avoiding Deadlock

Deadlocks Related to Scheduling

Locking Guidelines

Finding Deadlocks

Some Basic Guidelines for Threaded Code

Creating and Using Threads

Working With Multiprocessors

Underlying Architecture

Shared-Memory Multiprocessors

Peterson's Algorithm

Parallelizing a Loop on a Shared-Memory Parallel Computer

Examples of Threads Programs

Further Reading

A.  Extended Example: A Thread Pool Implementation

Index

Providing for Static Local Variables

Example 9-2 shows a problem that is similar to the errno problem, but involving static storage instead of global storage. The function gethostbyname(3NSL) is called with the computer name as its argument. The return value is a pointer to a structure that contains the required information for contacting the computer through network communications.

Example 9-2 The gethostbyname() Problem

struct hostent *gethostbyname(char *name) {
    static struct hostent result;
        /* Lookup name in hosts database */
        /* Put answer in result */
    return(&result);
}

A pointer that is returned to a local variable is generally not a good idea. Using a pointer works in this example because the variable is static. However, when two threads call this variable at once with different computer names, the use of static storage conflicts.

Thread-specific data could be used as a replacement for static storage, as in the errno problem. But, this replacement involves dynamic allocation of storage and adds to the expense of the call.

A better way to handle this kind of problem is to make the caller of gethostbyname() supply the storage for the result of the call. An additional output argument to the routine enables the caller to supply the storage. The additional output argument requires a new interface to the gethostbyname() function.

This technique is used in threads to fix many of these problems. In most cases, the name of the new interface is the old name with “_r” appended, as in gethostbyname_r(3NSL).