Multithreaded Programming Guide

pthread_attr_setstackaddr(3THR)

pthread_attr_setstackaddr(3THR) sets the thread stack address.

The stackaddr attribute defines the base of the thread's stack. If this is set to non-null (NULL is the default) the system initializes the stack at that address.

Prototype:

int	pthread_attr_setstackaddr(pthread_attr_t *tattr,void *stackaddr);
#include <pthread.h>

pthread_attr_t tattr;
void *base;
int ret;

base = (void *) malloc(PTHREAD_STACK_MIN + 0x4000);

/* setting a new address */
ret = pthread_attr_setstackaddr(&tattr, base);

In the previous example, base contains the address for the stack that the new thread uses. If base is NULL, then pthread_create(3T) allocates a stack for the new thread with at least PTHREAD_STACK_MIN bytes.

Return Values

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


EINVAL

The value of base or tattr is incorrect.

This example shows how to create a thread with a custom stack address.

#include <pthread.h>

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

stackbase = (void *) malloc(size);

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

/* setting the base address in the attribute */
ret = pthread_attr_setstackaddr(&tattr, stackbase);

/* only address specified in attribute tattr */
ret = pthread_create(&tid, &tattr, func, arg); 

This example shows how to create a thread with both a custom stack address and a custom stack size.

#include <pthread.h>

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

int size = PTHREAD_STACK_MIN + 0x4000;
stackbase = (void *) malloc(size);

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

/* setting the size of the stack also */
ret = pthread_attr_setstacksize(&tattr, size);

/* setting the base address in the attribute */
ret = pthread_attr_setstackaddr(&tattr, stackbase);

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