POSIX线程的栈管理


  • POSIX标准没有为线程的栈规定默认的大小,所以该值是根据实现而变化的;栈的最大容量也是由实现去定义。
  • 一旦超过栈的容量限制,程序会崩溃,或者数据损坏。
  • 可靠而又保证移植性的作法,是显式地设置栈的大小,不使用默认值。
  • 有些实现要求线程的栈放在内存的特殊的地方,此时要使用pthread_attr_setstackaddr()函数。
  1. #include <stdlib.h>   
  2. #include <pthread.h>   
  3.   
  4. // 通过调节三个参数,了解当前计算机的线程栈容量   
  5. #define NTHREADS    4   
  6. #define N           1000   
  7. #define MEGEXTRA    1000000   
  8.   
  9. pthread_attr_t attr;  
  10.   
  11. void *dowork(void *threadid)  
  12. {  
  13.     size_t mystacksize;  
  14.     pthread_attr_getstacksize (&attr, &mystacksize);  
  15.     printf("[WORKER THREAD %ld] Stack size = %li bytes \n", (long)threadid, mystacksize);  
  16.   
  17.     // 辅助线程的栈绝大部分耗在下面这个数组上了。   
  18.     // 因为给每个线程多分配了MEGEXTRA字节空间,故而运行没问题。   
  19.     // 可以尝试设置负数的MEGEXTRA,看程序如何报错。   
  20.     double A[N][N];  
  21.     for (int i=0; i<N; i++)  
  22.     {  
  23.         for (int j=0; j<N; j++)  
  24.         {  
  25.             A[i][j] = ((i*j)/3.452) + (N-i);  
  26.         }  
  27.     }  
  28.     return NULL;  
  29. }  
  30.   
  31. int _tmain(int argc, _TCHAR* argv[])  
  32. {  
  33.     size_t stacksize;  
  34.     long t;  
  35.   
  36.     pthread_attr_init(&attr);  
  37.     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);  
  38.   
  39.     pthread_attr_getstacksize (&attr, &stacksize);  
  40.     printf("[MASTER THREAD] Default stack size = %li\n", stacksize);  
  41.   
  42.     stacksize = sizeof(double) * N * N + MEGEXTRA;  
  43.     pthread_attr_setstacksize (&attr, stacksize);  
  44.     printf("[MASTER THREAD] Creating threads with stack size = %li bytes\n",stacksize);  
  45.   
  46.     pthread_t threads[NTHREADS];  
  47.     for(t=0; t<NTHREADS; t++)  
  48.     {  
  49.         int rc = pthread_create(&threads[t], &attr, dowork, (void *)t);  
  50.         if (rc)  
  51.         {  
  52.             printf("[MASTER THREAD] ERROR; return code from pthread_create() is %d\n", rc);  
  53.             exit(-1);  
  54.         }  
  55.     }  
  56.   
  57.     for(t=0; t<NTHREADS; t++)  
  58.     {  
  59.         pthread_join(threads[t], NULL);  
  60.     }  
  61.     return 0;  
  62. }  
我在WinXP上试验时,得到栈的默认大小是零,这是为什么?

相关内容