- POSIX标准没有为线程的栈规定默认的大小,所以该值是根据实现而变化的;栈的最大容量也是由实现去定义。
- 一旦超过栈的容量限制,程序会崩溃,或者数据损坏。
- 可靠而又保证移植性的作法,是显式地设置栈的大小,不使用默认值。
- 有些实现要求线程的栈放在内存的特殊的地方,此时要使用pthread_attr_setstackaddr()函数。
#include <stdlib.h>
#include <pthread.h>
// 通过调节三个参数,了解当前计算机的线程栈容量
#define NTHREADS 4
#define N 1000
#define MEGEXTRA 1000000
pthread_attr_t attr;
void *dowork(void *threadid)
{
size_t mystacksize;
pthread_attr_getstacksize (&attr, &mystacksize);
printf("[WORKER THREAD %ld] Stack size = %li bytes \n", (long)threadid, mystacksize);
// 辅助线程的栈绝大部分耗在下面这个数组上了。
// 因为给每个线程多分配了MEGEXTRA字节空间,故而运行没问题。
// 可以尝试设置负数的MEGEXTRA,看程序如何报错。
double A[N][N];
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
A[i][j] = ((i*j)/3.452) + (N-i);
}
}
return NULL;
}
int _tmain(int argc, _TCHAR* argv[])
{
size_t stacksize;
long t;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_attr_getstacksize (&attr, &stacksize);
printf("[MASTER THREAD] Default stack size = %li\n", stacksize);
stacksize = sizeof(double) * N * N + MEGEXTRA;
pthread_attr_setstacksize (&attr, stacksize);
printf("[MASTER THREAD] Creating threads with stack size = %li bytes\n",stacksize);
pthread_t threads[NTHREADS];
for(t=0; t<NTHREADS; t++)
{
int rc = pthread_create(&threads[t], &attr, dowork, (void *)t);
if (rc)
{
printf("[MASTER THREAD] ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
for(t=0; t<NTHREADS; t++)
{
pthread_join(threads[t], NULL);
}
return 0;
}
我在WinXP上试验时,得到栈的默认大小是零,这是为什么?