unix多线程时子线程的堆和栈
各位好,最近刚刚接触Unix的多线程(pthread),遇到一个比较郁闷的问题,子线程有时会卡住 ,它不会往下执行,也不会core。后来查出问题,是因为有个变量new时申请空间太大了。
研究了下aix的多线程时的进程模型,如下:
它说,创建一个线程时,会在进程的堆区分配一块,作为线程栈(thread stack)使用。那线程中new出来的堆数据,是放到哪一块呢?
我写个小程序测试了下,线程主体代码如下:
void thread_func(){ int i_val; printf("[线程%d]i_val = \t0x%016p\n",pthread_self(),&i_val); int* pi = new int(); if(pi == NULL) { fprintf(stderr,"分配内存失败\n"); return; } printf("[线程%d]pi = \t\t0x%016p\n",pthread_self(),pi); char* pMalloc; if((pMalloc = (char*) malloc(10)) == NULL) { return; } printf("[线程%d]pMalloc = \t\t0x%016p\n",pthread_self(),pMalloc); sleep(2);}
#include<pthread.h> #include<stdio.h>#include<stdlib.h>void* thread_func(void* arg){ int i_val; printf("[thread %d]i_val= \t0x%016p\n",pthread_self(),&i_val); int* pi = new int(); if(pi == NULL) { fprintf(stderr,"·Öä´Ã); } printf("[thread %d] pi = \t\t0x%016p\n",pthread_self(),pi); char* pMalloc; if((pMalloc = (char*) malloc(10)) == NULL) { } printf("[thread %d]pmalloc = \t\t0x%016p\n",pthread_self(),pMalloc);}int main(int argc,int argv[]){ int error; int *temptr; pthread_t thread_id1, thread_id2; pthread_create(&thread_id1,NULL,thread_func,NULL); pthread_create(&thread_id2,NULL,thread_func,NULL); if(error=pthread_join(thread_id1,NULL)) { perror("pthread_join"); exit(EXIT_FAILURE); } if(error=pthread_join(thread_id2, NULL)) { perror("pthread_join"); exit(EXIT_FAILURE); } return 0;}