以前曾经写过一篇关于thread stack size设置的文章,现在感觉有些地方没有说清楚,所以现在再讲一讲。
1)曾经有个问题,就是设置下去 stack size之后,再去读的时候返回的还是之前的数值。
原因没有正确使用POSIX threads 的接口。
下面的代码是可以正确的读出数值的:
#include <pthread.h>
#include <stdio.h>
void * thread_start(void *arg)
{
pthread_attr_t attr;
int size = 0;
//int *stackaddr = NULL;
// pthread_t * tid = (pthread_t *)arg;
pthread_getattr_np(pthread_self(), &attr);
pthread_attr_getstacksize(&attr, &size);
printf("stack size: %d KB\n", size/1024);
size *= 2;
if(pthread_attr_setstacksize(&attr, size) != 0)
{
printf("failed to set stack size\n");
}
pthread_attr_getstacksize(&attr, &size);
printf("size = %dKB\n", size/1024);
// char arr[1024 * 257];
}
int main(void)
{
pthread_t tid;
pthread_attr_t attr;
void *status = NULL;
pthread_attr_init(&attr);
// pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_attr_setstacksize(&attr, 256 * 1024);
pthread_create(&tid, &attr, &thread_start, NULL);
// pthread_exit(NULL);
pthread_attr_destroy(&attr);
pthread_join(tid, &status);
return 0;
}
输出为:
#./code/threadstack
stack size: 256 KB
size = 512KB
2)另外需要注意的一点是,线程的stack 大小只能在主线程里设置,而且一旦设置后,就固定下来而无法改变。
上面的这个代码在线程函数里去尝试修改线程的 stack 大小,虽然表面看成功了,但实际上线程的 stack 大小还是256KB!
这一点可以通过用 GDB 调试,观察程序的 内存映射里的 stack 区域的大小确认。
这在 pthread的 man 里也有说明:
A thread's stack size is fixed at the time of thread creation. Only the main thread can dynamically
grow its stack.