| C++ Programming Guide |
Multithreaded Programs
This chapter explains how to build multithreaded programs. It also discusses the use of exceptions and explains how to share C++ Standard Library objects across threads.
For more information about multithreading, see the Multithreaded Programming Guide, the C++ Library Reference, the Tools.h++ User's Guide, and the Standard C++ Library User's Guide.
9.1 Building Multithreaded Programs
All libraries shipped with the C++ compiler are multithreading-safe. If you want to build a multithreaded application, or if you want to link your application to a multithreaded library, you must compile and link your program with the
-mtoption. This option passes-D_REENTRANTto the preprocessor and passes-lthreadin the correct order told. For compatibility mode (-compat[=4]),the-mtoption ensures thatlibthreadis linked beforelibC. For standard mode (the default mode), the-mtoption ensures thatlibthreadis linked beforelibCrun.Do not link your application directly with
-lthreadbecause this causeslibthreadto be linked in an incorrect order.The following example shows the correct way to build a multithreaded application when the compilation and linking are done in separate steps:
example%CC -c -mt myprog.ccexample%CC -mt myprog.oThe following example shows the wrong way to build a multithreaded application:
example%CC -c -mt myprog.oexample%CC myprog.o -lthread<- libthread is linked incorrectly9.1.1 Indicating Multithreaded Compilation
You can check whether an application is linked to
libthreador not by using thelddcommand:
9.1.2 Using C++ Support Libraries With Threads and Signals
The C++ support libraries,
libCrun,libiostream,libCstd, andlibCare multithread safe but are notasyncsafe. This means that in a multithreaded application, functions available in the support libraries should not be used in signal handlers. Doing so can result in a deadlock situation.It is not safe to use the following in a signal handler in a multithreaded application:
- Iostreams
newanddeleteexpressions- Exceptions
9.2 Using Exceptions in a Multithreaded Program
The current exception-handling implementation is safe for multithreading; exceptions in one thread do not interfere with exceptions in other threads. However, you cannot use exceptions to communicate across threads; an exception thrown from one thread cannot be caught in another.
Each thread can set its own
terminate()orunexpected()function. Callingset_terminate()orset_unexpected()in one thread affects only the exceptions in that thread. The default function forterminate()isabort()for the main thread, andthr_exit()for other threads (see Section 5.5 Specifying Runtime Errors).
Note Thread cancellation (pthread_cancel(3T)) results in the destruction of automatic (local nonstatic) objects on the stack. When a thread is cancelled, the execution of local destructors is interleaved with the execution of cleanup routines that the user has registered withpthread_cleanup_push(). The local objects for functions called after a particular cleanup routine is registered are destroyed before that routine is executed.
9.3 Sharing C++ Standard Library Objects Between Threads
The C++ Standard Library (
libCstd), which is multithread-safe, makes sure that the internals of the library work properly in a multithreading environment. You will still need to lock around any library objects that you yourself share between threads (except foriostreamsandlocaleobjects).For example, if you instantiate a string, then create a new thread and pass that string to the thread by reference, then you must lock around write access to that string, since you are explicitly sharing the one string object between threads. (The facilities provided by the library to accomplish this task are described below.)
On the other hand, if you pass the string to the new thread by value, you do not need to worry about locking, even though the strings in the two different threads may be sharing a representation through Rogue Wave's "copy on write" technology. The library handles that locking automatically. You are only required to lock when making an object available to multiple threads explicitly, either by passing references between threads or by using global or static objects.
The following describes the locking (synchronization) mechanism used internally in the C++ Standard Library to ensure correct behavior in the presence of multiple threads.
The interface to this facility (including the names of files, macros, classes, and any class members) as well as the implementation are an internal detail of the library and are subject to change without notice. Backward compatibility is not guaranteed.
Two synchronization classes provide mechanisms for achieving multithreaded safety;
_RWSTDMutexand_RWSTDGuard.The
_RWSTDMutexclass provides a platform-independent locking mechanism through the following member functions:
void acquire()--Acquires a lock on self, or blocks until such a lock can be obtained.void release()--Releases a lock on self.
class _RWSTDMutex{public:_RWSTDMutex ();~_RWSTDMutex ();void acquire ();void release ();};The
_RWSTDGuardclass is a convenience wrapper class that encapsulates an object of_RWSTDMutexclass. An_RWSTDGuardobject attempts to acquire the encapsulated mutex in its constructor (throwing an exception of type::thread_error, derived fromstd::exception on error), and releases the mutex in its destructor (the destructor never throws an exception).
class _RWSTDGuard{public:_RWSTDGuard (_RWSTDMutex&);~_RWSTDGuard ();};Additionally, you can use the macro
_RWSTD_MT_GUARD(mutex)(formerly_STDGUARD) to conditionally create an object of the_RWSTDGuardclass in multithread builds. The object guards the remainder of the code block in which it is defined from being executed by multiple threads simultaneously. In single-threaded builds the macro expands into an empty expression.The following example illustrates the use of these mechanisms.
|
Sun Microsystems, Inc. Copyright information. All rights reserved. Feedback |
Library | Contents | Previous | Next | Index |