This chapter provides further details on various aspects of POSIX threads. We discuss the interaction of threads with aspects of the traditional UNIX API—in particular, signals and the process control primitives (fork(), exec(), and _exit()). We also provide an overview of the two POSIX threads implementations available on Linux—LinuxThreads and NPTL—and note where each of these implementations deviates from the SUSv3 specification of Pthreads.
Each thread has its own stack whose size is fixed when the thread is created. On Linux/x86-32, for all threads other than the main thread, the default size of the per-thread stack is 2 MB. (On some 64-bit architectures, the default size is higher; for example, it is 32 MB on IA-64.) The main thread has a much larger space for stack growth (refer to Figure 29-1, in Background Details of the Pthreads API).
Occasionally, it is useful to change the size of a thread’s stack. The pthread_attr_setstacksize() function sets a thread attribute (Thread Attributes) that determines the size of the stack in threads created using the thread attributes object. The related pthread_attr_setstack() function can be used to control both the size and the location of the stack, but setting the location of a stack can decrease application portability. The manual pages provide details of these functions.
One reason to change the size of per-thread stacks is to allow for larger stacks for threads that allocate large automatic variables or make nested function calls of great depth (perhaps because of recursion). Alternatively, an application may want to reduce the size of per-thread stacks to allow for a greater number of threads within a process. For example, on x86-32, where the user-accessible virtual address space is 3 GB, the default stack size of 2 MB means that we can create a maximum of around 1500 threads. (The precise maximum depends on how much virtual memory is consumed by the text and data segments, shared libraries, and so on.) The minimum stack that can be employed on a particular architecture can be determined by calling sysconf(_SC_THREAD_STACK_MIN). For the NPTL implementation on Linux/x86-32, this call returns the value 16,384.
Under the NPTL threading implementation, if the stack size resource limit (RLIMIT_STACK
) is set to anything other than unlimited, then it is used as the default stack size when creating new threads. This limit must be set before the program is executed, typically by using the ulimit -s shell built-in command (limit stacksize in the C shell) before executing the program. It is not sufficient to use setrlimit() within the main program to set the limit, because NPTL makes its determination of the default stack size during the run-time initialization that occurs before main() is invoked.