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, and change the behavior of alarm(2).

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.

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

This diagram summarizes the compile options:

Figure 7-1 Compilation Flowchart


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.

The behavior of the C library is undefined if a program is constructed with an ld command line that includes the following incorrect fragment:

	.o's ... -lc -lthread ... (this is incorrect)
 	.o's ... -lc -lpthread ... (this is incorrect)

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.