2012-05-17 82 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.