Multithreaded Programming Guide

Linking With libthread or libpthread

For POSIX threads behavior, load the libpthread library. For Solaris threads behavior, load the libthread library. Some POSIX programmers might want to link with -lthread to preserve the Solaris distinction between fork() and fork1(). All that -lpthread really does is to make fork() behave the same way as the Solaris fork1() call.

To use libthread, specify -lthread before -lc on the ld command line, or last on the cc command line.

To use libpthread, specify -lpthread before -lc on the ld command line, or last on the cc command line.

Prior to Solaris 9, you should not link a nonthreaded program with -lthread or -lpthread. Doing so establishes multithreading mechanisms at link time that are initiated at runtime. These slow down a single-threaded application, waste system resources, and produce misleading results when you debug your code.

In Solaris 9 and subsequent releases, linking a nonthreaded program with -lthread or -lpthread makes no semantic difference to the program. No extra threads or LWPs are created and the main (and only) thread executes as a traditional single-threaded process. The only effect on the program is to make system library locks become real locks (as opposed to dummy function calls) and you pay the price of acquiring uncontended locks.

Figure 7–1 summarizes the compile options.

Figure 7–1 Compilation Flowchart

Diagram showing compile options for POSIX, Solaris, and mixed usage

In mixed usage, you need to include both thread.h and pthread.h.

All calls to libthread and libpthread are no-ops if the application does not link -lthread or -lpthread. The runtime library libc has many predefined libthread and libpthread stubs that are null procedures. True procedures are interposed by libthread or libpthread when the application links both libc and the thread library.


Note –

For C++ programs that use threads, use the -mt option, rather than -lthread, to compile and link your application. The -mt option links with libthread and ensures proper library linking order. Using -lthread might cause your program to core dump.