POSIX线程的栈管理
文章由LinuxBoy分享于2019-04-01 03:04:12
POSIX线程的栈管理
- 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);
-
-
-
-
- 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上试验时,得到栈的默认大小是零,这是为什么?
评论暂时关闭