thread线程栈size及局部变量最大可分配size【转】

简介:

转自:http://blog.csdn.net/sunny04/article/details/46805261

进程是操作系统的最小资源管理单元, 线程是操作系统最小的执行单元。 一个进程可以有多个线程, 也就是说多个线程分享进程的资源,包括栈区,堆区,代码区,数据区等。

[cpp]  view plain  copy
  1. sundh@linhaoIPTV:~$ ulimit -a  
  2. core file size          (blocks, -c) 0  
  3. data seg size           (kbytes, -d) unlimited  
  4. scheduling priority             (-e) 0  
  5. file size               (blocks, -f) unlimited  
  6. pending signals                 (-i) 31675  
  7. max locked memory       (kbytes, -l) 64  
  8. max memory size         (kbytes, -m) unlimited  
  9. open files                      (-n) 1024  
  10. pipe size            (512 bytes, -p) 8  
  11. POSIX message queues     (bytes, -q) 819200  
  12. real-time priority              (-r) 0  
  13. stack size              (kbytes, -s) 8192  
  14. cpu time               (seconds, -t) unlimited  
  15. max user processes              (-u) 31675  
  16. virtual memory          (kbytes, -v) unlimited  
  17. file locks                      (-x) unlimited  

 

32bit x86机器上面,执行ulimit -a的命令, 可以看到 

stack size              (kbytes, -s) 8192    这是否说明在线程中可以分配8M的局部变量(或者说分配7M的局部变量,还有1M的空间存储其他的局部变量或者寄存器状态信息(例如bp等)或者函数压栈信息等)

写代码验证如下:

[cpp]  view plain  copy
  1. //test2.cpp  
  2. #include <iostream>  
  3. #include <string.h>  
  4. #include <pthread.h>  
  5. #include <stdio.h>  
  6.   
  7. using namespace std;  
  8.   
  9. void* func(void*a)  
  10. {  
  11.     cout << "enter func" << endl;  
  12.     cout << "enter func" << endl;  
  13.     int b[1024*1024*2] = {0};  
  14. }  
  15.   
  16. int main()  
  17. {  
  18.     int a[1024*1024*3/2]={0};  
  19.     pthread_t  pthread ;  
  20.     pthread_create(&pthread, NULL, func, NULL);  
  21.     cout << "This is a test" << endl;  
  22.     //pthread_join(pthread, NULL);  
  23.     return 0;  
  24. }  

g++ -g -o test2 test2.cpp -lpthread
sundh@linux:~$ gdb test2
GNU gdb (GDB) 7.5-ubuntu
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/sundh/test2...done.
(gdb) r
Starting program: /home/sundh/test2
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/i386-linux-gnu/libthread_db.so.1".
[New Thread 0xb7cc1b40 (LWP 10313)]

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0xb7cc1b40 (LWP 10313)]
func (a=0x0) at test2.cpp:10
10          cout << "enter func" << endl;
(gdb)

GDB调试结果如上。   main() 函数中分配1.5M的局部变量,是不会报错的, 但子线程中分配2M的局部变量,就会coredump。 可见,只能分配不大于2M的局部变量,但ulimit -a 查询到的stack size 为8M。


猜想:  线程只能分配不大于 1/4 大小的 stack size 给 局部变量, 这应该是操作系统的规定。(没在网络上面找到相关的文档说明)

那我们现在开始验证我们的猜想:


通过 ulimit -s命令修改默认的栈大小,  下面程序分配5M的局部变量, 也就是说线程栈的大小要 > 20M(5M*4)

[cpp]  view plain  copy
  1. //test1.cpp  
  2. #include <iostream>  
  3. #include <string.h>  
  4. #include <pthread.h>  
  5. #include <stdio.h>  
  6.   
  7. using namespace std;  
  8.   
  9. void* func(void*a)  
  10. {  
  11.     cout << "enter func" << endl;  
  12.     cout << "enter func" << endl;  
  13.     int b[1024*1024*5] = {0};  
  14. }  
  15.   
  16. int main()  
  17. {  
  18.     int a[1024*1024*5]={0};  
  19.     pthread_t  pthread ;  
  20.     pthread_create(&pthread, NULL, func, NULL);  
  21.     cout << "This is a test" << endl;  
  22.     //pthread_join(pthread, NULL);  
  23.     return 0;  
  24. }  

ulimit -s 21504 (也就是21M) , 把默认的stack size设置为21M

sundh@linux:~ulimit−s21504sundh@linux: ulimit−s21504sundh@linux:  g++ -g -o test2 test2.cpp -lpthread
sundh@linux:~$ ./test2
This is a testenter func
enter func

可以成功运行, 验证了我们的猜想。

ulimit -s 修改 stack size, 也可以通过 pthread_attr_setstacksize() 来修改。 使用ulimit的一个后果就是它会影响到同一环境(同一shell或者终端)下后续启动的所有程序,如果修改成启动时设置的话就会影响到整个系统。 所以大部分情况下还是使用pthread_attr_setstacksize()

代码如下:

[cpp]  view plain  copy
  1. #include <pthread.h>  
  2. #include <string.h>  
  3. #include <stdio.h>  
  4. #include <stdlib.h>  
  5. #include <unistd.h>  
  6. #include <errno.h>  
  7. #include <ctype.h>  
  8.   
  9. #define handle_error_en(en, msg) \  
  10.         do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)  
  11.   
  12. #define handle_error(msg) \  
  13.         do { perror(msg); exit(EXIT_FAILURE); } while (0)  
  14.   
  15. struct thread_info {    /* Used as argument to thread_start() */  
  16.     pthread_t thread_id;        /* ID returned by pthread_create() */  
  17.     int       thread_num;       /* Application-defined thread # */  
  18.     char     *argv_string;      /* From command-line argument */  
  19. };  
  20.   
  21. /* Thread start function: display address near top of our stack, 
  22.    and return upper-cased copy of argv_string */  
  23.   
  24. static void *  
  25. thread_start(void *arg)  
  26. {  
  27.     struct thread_info *tinfo = arg;  
  28.     char *uargv, *p;  
  29.   
  30.      <span style="color:#FF0000;">int a[1024*1024*5] = {0};</span>  
  31.  printf("Thread %d: top of stack near %p; argv_string=%s\n",  
  32.             tinfo->thread_num, &p, tinfo->argv_string);  
  33.   
  34.    uargv = strdup(tinfo->argv_string);  
  35.     if (uargv == NULL)  
  36.         handle_error("strdup");  
  37.   
  38.    for (p = uargv; *p != '\0'; p++)  
  39.         *p = toupper(*p);  
  40.   
  41.    return uargv;  
  42. }  
  43.   
  44. int  
  45. main(int argc, char *argv[])  
  46. {  
  47.     int s, tnum, opt, num_threads;  
  48.     struct thread_info *tinfo;  
  49.     pthread_attr_t attr;  
  50.     int stack_size;  
  51.     void *res;  
  52.   
  53.    /* The "-s" option specifies a stack size for our threads */  
  54.   
  55.    stack_size = -1;  
  56.     while ((opt = getopt(argc, argv, "s:")) != -1) {  
  57.         switch (opt) {  
  58.         case 's':  
  59.             stack_size = strtoul(optarg, NULL, 0);  
  60.             break;  
  61.   
  62.        default:  
  63.             fprintf(stderr, "Usage: %s [-s stack-size] arg...\n",  
  64.                     argv[0]);  
  65.             exit(EXIT_FAILURE);  
  66.         }  
  67.     }  
  68.   
  69.    num_threads = argc - optind;  
  70.   
  71.    /* Initialize thread creation attributes */  
  72.   
  73.    s = pthread_attr_init(&attr);  
  74.     if (s != 0)  
  75.         handle_error_en(s, "pthread_attr_init");  
  76.   
  77.    if (stack_size > 0) {  
  78.         s = <span style="color:#FF0000;">pthread_attr_setstacksize</span>(&attr, stack_size);  
  79.         if (s != 0)  
  80.             handle_error_en(s, "pthread_attr_setstacksize");  
  81.     }  
  82.   
  83.    /* Allocate memory for pthread_create() arguments */  
  84.   
  85.    tinfo = calloc(num_threads, sizeof(struct thread_info));  
  86.     if (tinfo == NULL)  
  87.         handle_error("calloc");  
  88.   
  89.    /* Create one thread for each command-line argument */  
  90.   
  91.    for (tnum = 0; tnum < num_threads; tnum++) {  
  92.         tinfo[tnum].thread_num = tnum + 1;  
  93.         tinfo[tnum].argv_string = argv[optind + tnum];  
  94.   
  95.        /* The pthread_create() call stores the thread ID into 
  96.            corresponding element of tinfo[] */  
  97.   
  98.        s = pthread_create(&tinfo[tnum].thread_id, &attr,  
  99.                            &thread_start, &tinfo[tnum]);  
  100.         if (s != 0)  
  101.             handle_error_en(s, "pthread_create");  
  102.     }  
  103.   
  104.    /* Destroy the thread attributes object, since it is no 
  105.        longer needed */  
  106.   
  107.    s = pthread_attr_destroy(&attr);  
  108.     if (s != 0)  
  109.         handle_error_en(s, "pthread_attr_destroy");  
  110.   
  111.    /* Now join with each thread, and display its returned value */  
  112.   
  113.    for (tnum = 0; tnum < num_threads; tnum++) {  
  114.         s = pthread_join(tinfo[tnum].thread_id, &res);  
  115.         if (s != 0)  
  116.             handle_error_en(s, "pthread_join");  
  117.   
  118.        printf("Joined with thread %d; returned value was %s\n",  
  119.                 tinfo[tnum].thread_num, (char *) res);  
  120.         free(res);      /* Free memory allocated by thread */  
  121.     }  
  122.   
  123.    free(tinfo);  
  124.     exit(EXIT_SUCCESS);  
  125. }  

$ ./a.out -s 0x1600000 hola salut servus   (0x1500000  == 20M,0x1600000==21M  )

Thread 1: top of stack near 0xb7d723b8; argv_string=hola

Thread 2: top of stack near 0xb7c713b8; argv_string=salut

Thread 3: top of stack near 0xb7b703b8; argv_string=servus

Joined with thread 1; returned value was HOLA

Joined with thread 2; returned value was SALUT

Joined with thread 3; returned value was SERVUS

程序可以正常运行。 这里需要注意的一点是,主线程还是使用系统默认的stack size,也即8M, 不能在main() 里面声明超过2M的局部变量,创建子线程的时候调用了pthread_attr_setstacksize(), 修改stack size为21M,然后就能在子线程中声明5M的局部变量了。








本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/sky-heaven/p/7654950.html,如需转载请自行联系原作者

相关实践学习
阿里云图数据库GDB入门与应用
图数据库(Graph Database,简称GDB)是一种支持Property Graph图模型、用于处理高度连接数据查询与存储的实时、可靠的在线数据库服务。它支持Apache TinkerPop Gremlin查询语言,可以帮您快速构建基于高度连接的数据集的应用程序。GDB非常适合社交网络、欺诈检测、推荐引擎、实时图谱、网络/IT运营这类高度互连数据集的场景。 GDB由阿里云自主研发,具备如下优势: 标准图查询语言:支持属性图,高度兼容Gremlin图查询语言。 高度优化的自研引擎:高度优化的自研图计算层和存储层,云盘多副本保障数据超高可靠,支持ACID事务。 服务高可用:支持高可用实例,节点故障迅速转移,保障业务连续性。 易运维:提供备份恢复、自动升级、监控告警、故障切换等丰富的运维功能,大幅降低运维成本。 产品主页:https://www.aliyun.com/product/gdb
相关文章
|
存储 C语言 C++
【C++数据结构——栈与队列】顺序栈的基本运算(头歌实践教学平台习题)【合集】
本关任务:编写一个程序实现顺序栈的基本运算。开始你的任务吧,祝你成功!​ 相关知识 初始化栈 销毁栈 判断栈是否为空 进栈 出栈 取栈顶元素 1.初始化栈 概念:初始化栈是为栈的使用做准备,包括分配内存空间(如果是动态分配)和设置栈的初始状态。栈有顺序栈和链式栈两种常见形式。对于顺序栈,通常需要定义一个数组来存储栈元素,并设置一个变量来记录栈顶位置;对于链式栈,需要定义节点结构,包含数据域和指针域,同时初始化栈顶指针。 示例(顺序栈): 以下是一个简单的顺序栈初始化示例,假设用C语言实现,栈中存储
1443 77
|
Arthas 监控 Java
Arthas thread(查看当前JVM的线程堆栈信息)
Arthas thread(查看当前JVM的线程堆栈信息)
2564 10
|
编译器 C语言 C++
栈区的非法访问导致的死循环(x64)
这段内容主要分析了一段C语言代码在VS2022中形成死循环的原因,涉及栈区内存布局和数组越界问题。代码中`arr[15]`越界访问,修改了变量`i`的值,导致`for`循环条件始终为真,形成死循环。原因是VS2022栈区从低地址到高地址分配内存,`arr`数组与`i`相邻,`arr[15]`恰好覆盖`i`的地址。而在VS2019中,栈区先分配高地址再分配低地址,因此相同代码表现不同。这说明编译器对栈区内存分配顺序的实现差异会导致程序行为不一致,需避免数组越界以确保代码健壮性。
408 0
栈区的非法访问导致的死循环(x64)
|
存储 C++ 索引
【C++数据结构——栈与队列】环形队列的基本运算(头歌实践教学平台习题)【合集】
【数据结构——栈与队列】环形队列的基本运算(头歌实践教学平台习题)【合集】初始化队列、销毁队列、判断队列是否为空、进队列、出队列等。本关任务:编写一个程序实现环形队列的基本运算。(6)出队列序列:yzopq2*(5)依次进队列元素:opq2*(6)出队列序列:bcdef。(2)依次进队列元素:abc。(5)依次进队列元素:def。(2)依次进队列元素:xyz。开始你的任务吧,祝你成功!(4)出队一个元素a。(4)出队一个元素x。
713 13
【C++数据结构——栈与队列】环形队列的基本运算(头歌实践教学平台习题)【合集】
232.用栈实现队列,225. 用队列实现栈
在232题中,通过两个栈(`stIn`和`stOut`)模拟队列的先入先出(FIFO)行为。`push`操作将元素压入`stIn`,`pop`和`peek`操作则通过将`stIn`的元素转移到`stOut`来实现队列的顺序访问。 225题则是利用单个队列(`que`)模拟栈的后入先出(LIFO)特性。通过多次调整队列头部元素的位置,确保弹出顺序符合栈的要求。`top`操作直接返回队列尾部元素,`empty`判断队列是否为空。 两题均仅使用基础数据结构操作,展示了栈与队列之间的转换逻辑。
|
算法 调度 C++
STL——栈和队列和优先队列
通过以上对栈、队列和优先队列的详细解释和示例,希望能帮助读者更好地理解和应用这些重要的数据结构。
475 11
☀☀☀☀☀☀☀有关栈和队列应用的oj题讲解☼☼☼☼☼☼☼
### 简介 本文介绍了三种数据结构的实现方法:用两个队列实现栈、用两个栈实现队列以及设计循环队列。具体思路如下: 1. **用两个队列实现栈**: - 插入元素时,选择非空队列进行插入。 - 移除栈顶元素时,将非空队列中的元素依次转移到另一个队列,直到只剩下一个元素,然后弹出该元素。 - 判空条件为两个队列均为空。 2. **用两个栈实现队列**: - 插入元素时,选择非空栈进行插入。 - 移除队首元素时,将非空栈中的元素依次转移到另一个栈,再将这些元素重新放回原栈以保持顺序。 - 判空条件为两个栈均为空。
|
存储 C语言 C++
【C++数据结构——栈与队列】链栈的基本运算(头歌实践教学平台习题)【合集】
本关任务:编写一个程序实现链栈的基本运算。开始你的任务吧,祝你成功!​ 相关知识 初始化栈 销毁栈 判断栈是否为空 进栈 出栈 取栈顶元素 初始化栈 概念:初始化栈是为栈的使用做准备,包括分配内存空间(如果是动态分配)和设置栈的初始状态。栈有顺序栈和链式栈两种常见形式。对于顺序栈,通常需要定义一个数组来存储栈元素,并设置一个变量来记录栈顶位置;对于链式栈,需要定义节点结构,包含数据域和指针域,同时初始化栈顶指针。 示例(顺序栈): 以下是一个简单的顺序栈初始化示例,假设用C语言实现,栈中存储整数,最大
511 9
【C++数据结构——栈和队列】括号配对(头歌实践教学平台习题)【合集】
【数据结构——栈和队列】括号配对(头歌实践教学平台习题)【合集】(1)遇到左括号:进栈Push()(2)遇到右括号:若栈顶元素为左括号,则出栈Pop();否则返回false。(3)当遍历表达式结束,且栈为空时,则返回true,否则返回false。本关任务:编写一个程序利用栈判断左、右圆括号是否配对。为了完成本关任务,你需要掌握:栈对括号的处理。(1)遇到左括号:进栈Push()开始你的任务吧,祝你成功!测试输入:(()))
751 7
|
Java C# Python
线程等待(Thread Sleep)
线程等待是多线程编程中的一种同步机制,通过暂停当前线程的执行,让出CPU时间给其他线程。常用于需要程序暂停或等待其他线程完成操作的场景。不同语言中实现方式各异,如Java的`Thread.sleep(1000)`、C#的`Thread.Sleep(1000)`和Python的`time.sleep(1)`。使用时需注意避免死锁,并考虑其对程序响应性的影响。
536 8

热门文章

最新文章