先來講說線程內存相關的東西,主要有下面幾條:
- 進程中的所有的線程共享相同的地址空間。
- 任何聲明為static/extern的變量或者堆變量可以被進程內所有的線程讀寫。
- 一個線程真正擁有的唯一私有儲存是處理器寄存器。
- 線程??梢酝ㄟ^暴露棧地址的方式與其它線程進行共享。
有大數據量處理的應用中,有時我們有必要在??臻g分配一個大的內存塊或者要分配很多小的內存塊,但是線程的??臻g的最大值在線程創建的時候就已經定下來了,如果棧的大小超過個了個值,系統將訪問未授權的內存塊,毫無疑問,再來的肯定是一個段錯誤??墒菦]辦法,你還是不得不分配這些內存,于是你開會為分配一個整數值而動用malloc這種超級耗時的操作。當然,在你的需求可以評估的情況下,你的需求還是可以通過修改線程的棧空間的大小來改變的。
下面的我們用pthread_attr_getstacksize和pthread_attr_setstacksize的方法來查看和設置線程的??臻g。
注意:
下面的測試代碼在我自己的機子上(ubuntu6.06,ubuntu6.10,redhat 9,
gentoo)通過了測試,但是很奇怪的是在我同事的機子上,無論是改變環境,還是想其它方法都不能正常的運行
。在網上查了一下,很多人也存在同樣的問題,至今不知道為何。
linux線程的實現方式決定了對進程的限制同樣加在了線程身上:)所以,有問題,請參見<pthread之線程??臻g(2)(進行棧)
直接看代碼吧,只有一個C文件(thread_attr.c)
#include <limits.h>
#include <pthread.h>
#include "errors.h"
//線程體,在棧中分配一個大小為15M的空間,并進行讀寫
void *thread_routine (void *arg)
{
printf ("The thread is here\n");
//棧大小為16M,如果直接分配16M的棧空間,會出現段錯誤 ,因為棧中還有其它的
//變量要放署
char p[1024*1024*15];
int i=1024*1024*15;
//確定內存分配的確成功了
while(i--)
{
p[i] = 3;
}
printf( "Get 15M Memory!!!\n" );
//分配更多的內存(如果分配1024*1020*512的話就會出現段錯誤)
char p2[ 1024 * 1020 + 256 ];
memset( p2, 0, sizeof( char ) * ( 1024 * 1020 + 256 ) );
printf( "Get More Memory!!!\n" );
return NULL;
}
int main (int argc, char *argv[])
{
pthread_t thread_id;
pthread_attr_t thread_attr;
size_t stack_size;
int status;
status = pthread_attr_init (&thread_attr);
if (status != 0)
err_abort (status, "Create attr");
status = pthread_attr_setdetachstate (
&thread_attr, PTHREAD_CREATE_DETACHED);
if (status != 0)
err_abort (status, "Set detach");
//通常出現的問題之一,下面的宏沒有定義
#ifdef _POSIX_THREAD_ATTR_STACKSIZE
//得到當前的線程棧大小
status = pthread_attr_getstacksize (&thread_attr, &stack_size);
if (status != 0)
err_abort (status, "Get stack size");
printf ("Default stack size is %u; minimum is %u\n",
stack_size, PTHREAD_STACK_MIN);
//設置當前的線程的大小
status = pthread_attr_setstacksize (
&thread_attr, PTHREAD_STACK_MIN*1024);
if (status != 0)
err_abort (status, "Set stack size");
//得到當前的線程棧的大小
status = pthread_attr_getstacksize (&thread_attr, &stack_size);
if (status != 0)
err_abort (status, "Get stack size");
printf ("Default stack size is %u; minimum is %u\n",
stack_size, PTHREAD_STACK_MIN);
#endif
int i = 5;
//分配5個具有上面的屬性的線程體
while(i--)
{
status = pthread_create (
&thread_id, &thread_attr, thread_routine, NULL);
if (status != 0)
err_abort (status, "Create thread");
}
getchar();
printf ("Main exiting\n");
pthread_exit (NULL);
return 0;
}
看看執行過程:
dongq@DongQ_Lap
~/workspace/test/pthread_attr $ make
cc -pthread -g -DDEBUG -lrt -o
thread_attr thread_attr.c
dongq@DongQ_Lap ~/workspace/test/pthread_attr $
./thread_attr
Default stack size is 8388608; minimum is 16384
//默認的棧大小為8M
Default stack size is 16777216; minimum is 16384
//設置后的結果為16M
The thread is here
The thread is here
The thread is
here
The thread is here
The thread is here
Get 15M Memory!!!
Get
More Memory!!!
Get 15M Memory!!!
Get More Memory!!!
Get 15M
Memory!!!
Get 15M Memory!!!
Get More Memory!!!
Get More
Memory!!!
Get 15M Memory!!!
Get More Memory!!!
Main exiting