Sun Studio 12: C++ User's Guide

11.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 –mt option. This option passes –D_REENTRANT to the preprocessor and passes –lthread in the correct order to ld. For compatibility mode (–compat[=4]), the –mt option ensures that libthread is linked before libC. For standard mode (the default mode), the -mt option ensures that libthread is linked before libCrun.

Do not link your application directly with –lthread because this causes libthread to 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.cc
example% CC -mt myprog.o

The following example shows the wrong way to build a multithreaded application:


example% CC -c -mt myprog.o
example% CC myprog.o -lthread < -libthread is linked incorrectly

11.1.1 Indicating Multithreaded Compilation

You can check whether an application is linked to libthread or not by using the ldd command:


example% CC -mt myprog.cc
example% ldd a.out
libm.so.1 =>      /usr/lib/libm.so.1
libCrun.so.1 =>   /usr/lib/libCrun.so.1
libthread.so.1 => /usr/lib/libthread.so.1
libc.so.1 =>      /usr/lib/libc.so.1
libdl.so.1 =>     /usr/lib/libdl.so.1

11.1.2 Using C++ Support Libraries With Threads and Signals

The C++ support libraries, libCrun, libiostream, libCstd, and libC are multithread safe but are not async safe. 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: