Stack allocation

QNX SDP8.0Programmer's GuideDeveloper

Each thread has its own stack that you can allocate yourself or have the system manage.

The pthread_attr_t structure includes members that specify a new thread's stack address and size; pthread_attr_init() sets the default values, and you can use pthread_attr_setstackaddr() and pthread_attr_setstacksize() to override them. The values of the stack address and size members of this structure control the type of stack allocation that occurs when you create a thread:

Stack address Stack size Allocation
NULL 0 Automatic (the default)
NULL Desired size Partly automatic
Non-NULL Size of the allocated area Manual

Let's compare the types of allocation:

Automatic
The pthread_create() function allocates a stack for the thread. The default size for both x86_64 and AArch64 architectures is 256 KB.

The stack is followed by an inaccessible guard page which helps to detect stack overflow. The guard page exists only in virtual memory; there's no physical memory allocated for it.

When the thread exits, the process manager automatically deallocates the stack.

Partly automatic
The pthread_create() function allocates a stack for the thread of the size you specified rounded up to a multiple of the page size (4 KB) and followed by a guard page.
Manual
The process manager uses the stack that you allocated for the thread. It's up to you to allocate enough space for the thread, and no guard page is provided. The process manager doesn't deallocate the stack when the thread exits.
Note:
If you specify a stack size (for partly automatic or manual allocation), it should be the size that you want plus PTHREAD_STACK_MIN, which is the amount of space that the thread needs for its thread local storage and other overhead.

A process's main thread starts with an automatically allocated 512 KB stack, but it isn't deleted when the main thread goes away (e.g., calls pthread_exit() or is cancelled). The main thread's stack includes the command-line arguments and environment variables, which other threads might still need. To specify the stack size for the main thread, use qcc's -N option.

Page updated: