POSIX thread的 stack大小设置(之二)

以前曾经写过一篇关于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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值