工作中遇到一次这样的问题:栈上的空间不够用了,导致stack overflow,程序crash,并且coredump被写乱了。
这里用小例子,记录这样的问题。
【代码】
#include <pthread.h> #include <string.h> #include <unistd.h> #include <stdio.h> #define STACK_BUFFER_SIZE 10240 void * thread_func1(void * arg) { char buffer[STACK_BUFFER_SIZE]; int i = 0; while (i < 5) { ++i; printf("Thread #1, %d\n", i); sleep(1); } return 0; } void * thread_func2(void * arg) { char buffer[STACK_BUFFER_SIZE]; int i = 0; while (i < 5) { ++i; printf("Thread #2, %d\n", i); sleep(1); } return 0; } int main(int argc, char * argv[]) { pthread_t tid1, tid2; pthread_create(&tid1, NULL, thread_func1, NULL); pthread_create(&tid2, NULL, thread_func2, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); return 0; }
1.
g++ main.cpp -o t -lpthread ulimit -s 20 ./t没有crash
gdb t (gdb) b main.cpp:11当两个工作线程都起来后,停止断点时,观察thread信息
(gdb) i threads 3 Thread 0x7ffff7fe5700 (LWP 22751) 0x00007ffff71393bd in nanosleep () from /lib64/libc.so.6 * 2 Thread 0x7ffff7ff9700 (LWP 22750) thread_func1 (arg=0x0) at main.cpp:12 1 Thread 0x7ffff7fe7720 (LWP 22747) 0x00007ffff7bc80ad in pthread_join () from /lib64/libpthread.so.00x7ffff7ff9700 - 0x7ffff7fe7720 = 73696
直接运行 ./t,没有crash
2.
待续