Multithreaded Programming Guide

Setting the Stack Address and Size

pthread_attr_setstack(3C) sets the thread stack address and size.

pthread_attr_setstack(3C) Syntax

int pthread_attr_setstack(pthread_attr_t *tattr,void *stackaddr, size_t stacksize);
#include <pthread.h> 
#include <limits.h>
pthread_attr_t tattr; 
void *base; 
size_t size; 
int ret; 
base = (void *) malloc(PTHREAD_STACK_MIN + 0x4000); 
/* setting a new address and size */ 
ret = pthread_attr_setstack(&tattr, base,PTHREAD_STACK_MIN + 0x4000);

The stackaddr attribute defines the base (low address) of the thread's stack. The stacksize attribute specifies the size of the stack. If stackaddr is set to non-null, rather than the NULL default, the system initializes the stack at that address, assuming the size to be stacksize.

base contains the address for the stack that the new thread uses. If base is NULL, then pthread_create(3C) allocates a stack for the new thread with at least stacksize bytes.

pthread_attr_setstack(3C) Return Values

pthread_attr_setstack() returns zero after completing successfully. Any other return value indicates that an error occurred. If the following condition occurs, the function fails and returns the corresponding value.



The value of base or tattr is incorrect. The value of stacksize is less than PTHREAD_STACK_MIN.

The following example shows how to create a thread with a custom stack address and size.

#include <pthread.h>

pthread_attr_t tattr;
pthread_t tid;
int ret;
void *stackbase;
size_t size;

/* initialized with default attributes */
ret = pthread_attr_init(&tattr);

/* setting the base address and size of the stack */
ret = pthread_attr_setstack(&tattr, stackbase,size);

/* address and size specified */
ret = pthread_create(&tid, &tattr, func, arg);