2012-05-17 85 views
1

我写了一个小程序来创建线程并更改它们的默认堆栈大小,但在我的情况。当我更改属性后打印堆栈大小时,我仍将堆栈大小显示为默认堆栈大小。为什么不能创建堆栈大小小于默认大小的线程?

 # include<iostream> 
     # include<pthread.h> 
     # include<stdio.h> 
     # define size 10 
     using namespace std; 
     pthread_attr_t attr; 

     void* sum(void * threadid) 
     { 
      static int sum =0; 
      sum=sum+5; 
      long id=(long)threadid; 
      size_t mystacksize; 
      pthread_attr_getstacksize(&attr,&mystacksize); 
      cout << " stack size "<< mystacksize <<endl; 
     } 
     int main() 
     { 
     int rc; 
     long t=0; 
     pthread_t threads[5]; //number of different thread to br creatd 
     size_t stacksize; 
     pthread_attr_init(&attr); 
     pthread_attr_getstacksize(&attr,&stacksize); //gets the default stack size 
                 //allocated for thread 
     cout <<" Default stack size is : " << stacksize <<endl; 
     stacksize=size; 
     pthread_attr_setstacksize(&attr,stacksize); //sets a new stacksize for thread 
      for(t=0;t<5;t++) 
      { 
       rc=pthread_create(&threads[t],&attr,sum,(void*)t); 
       if(rc) 
       cout << "thread creation failed with id : " << t <<endl; 
      } 
     pthread_exit(NULL); 
     return 0; 
     } 

输出为: -

  Default stack size is : 8388608 
      stack size : 8388608 
      stack size : 8388608 
      stack size : 8388608 
      stack size : 8388608 
      stack size : 8388608 

还要注意的是,如果我尝试和增加stacksize大于default size我是能够成功地做到这一点。

+0

请添加一个语言标记。我假设这是C/C++。 – Gray

+0

为什么你想要一个较小的堆栈大小? –

+0

@HotLicks我是一个在线程概念的新手,只是少了些东西 – Invictus

回答

4

期望能够使用十个字节的堆栈大小是疯狂的。

您是否阅读pthread_attr_setstacksize手册页?你检查了呼叫pthread_attr_setstacksize的返回值吗?

在我的系统(GNU/Linux)的手册页说:

pthread_attr_setstacksize() can fail with the following error: 

    EINVAL The stack size is less than PTHREAD_STACK_MIN (16384) bytes.