Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get and Set the stack size of thread attribute in C
To get and set the stack size of thread attribute in C, we use the pthread_attr_getstacksize() and pthread_attr_setstacksize() functions. These functions allow us to query and modify the minimum stack size allocated to a thread's stack.
Syntax
int pthread_attr_getstacksize(const pthread_attr_t *attr, size_t *stacksize); int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);
pthread_attr_getstacksize()
This function retrieves the current stack size from a thread attribute object. It returns 0 on success, otherwise returns an error number.
Parameters:
- attr − Pointer to the thread attribute object
- stacksize − Pointer to store the retrieved stack size in bytes
pthread_attr_setstacksize()
This function sets a new stack size for a thread attribute object. It returns 0 on success, otherwise returns an error number.
Parameters:
- attr − Pointer to the thread attribute object
- stacksize − New stack size in bytes to be set
Note: To compile and run this program, use: gcc program.c -lpthread
Example
Here's a complete example demonstrating how to get and set thread stack size −
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int main() {
size_t stacksize;
pthread_attr_t attr;
/* Initialize the thread attribute object */
pthread_attr_init(&attr);
/* Get current stack size */
pthread_attr_getstacksize(&attr, &stacksize);
printf("Default stack size = %zu bytes
", stacksize);
/* Set new stack size */
pthread_attr_setstacksize(&attr, 65536);
/* Get the updated stack size */
pthread_attr_getstacksize(&attr, &stacksize);
printf("New stack size = %zu bytes
", stacksize);
/* Destroy the attribute object */
pthread_attr_destroy(&attr);
return 0;
}
Default stack size = 8388608 bytes New stack size = 65536 bytes
Key Points
- Always initialize thread attributes with
pthread_attr_init()before use - The stack size must be at least
PTHREAD_STACK_MINbytes - Use
%zuformat specifier forsize_tvalues inprintf() - Remember to destroy attribute objects with
pthread_attr_destroy()
Conclusion
The pthread_attr_getstacksize() and pthread_attr_setstacksize() functions provide control over thread stack allocation. Proper stack size management is crucial for thread performance and memory usage in multithreaded applications.
