The
pthread_attr_getguardsize() and
pthread_attr_setguardsize() functions get and set
guardsize in the
attr object. If
guardsize is larger than 0, the system reserves an additional region of guarded memory of at least
guardsize bytes at the end of the thread's stack for each new thread created by using
attr.
The guarded area is understood to be pages of memory that are protected from read and write access. While the guarded area should be rounded by the system page size, the actual default size is implementation-defined. In
NetBSD the default
guardsize is
_SC_PAGESIZE, the system page size.
The rationale behind
guardsize is two-fold:
1.
On the one hand, it provides protection against overflow of the stack pointer. If there is a guard area and a thread overflows its stack pointer into this extra memory area, it should receive a SIGSEGV signal or experience other comparable fatal error condition. Note that if a thread allocates large data structures on stack, it may be necessary to raise the default guardsize in order to detect stack overflows.
2.
On the other hand, the overflow protection may waste system resources if an application that creates a large number of threads knows that it will never overflow the stack. In this case it is possible to set guardsize to 0.
If
pthread_attr_setstack(3) or
pthread_attr_setstackaddr(3) is used to set the stack address attribute in
attr, the guard size attribute is ignored and no guard area will be allocated; it is the responsibility of the application to handle the overflow conditions.