每个线程都有一个堆栈那么,这个堆栈多大呢?
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES
-那默认大小又是多少?
写个小程序算一下~
#include
#include
#define STACK_SIZE 0.5*1024*1024
DWORD WINAPI ThreadFunc(PVOID pvParam)
{
DWORD dwRet = 0;
printf("%-3d:0x%x\n",pvParam,&dwRet);
return dwRet;
}
int
main(int,char**)
{
DWORD dwTid;
printf("Main:0x%x\n",&dwTid);
for(int i&#61;0;i<50;i&#43;&#43;)
CreateThread(NULL,STACK_SIZE,ThreadFunc,(PVOID)i,0,&dwTid); // 莫小注:原作者这处代码有错,这不能修改线程栈大小
Sleep(2000);
return 0;
}
输出:
Main:0x12ff78
0 :0x50ffb0
1 :0x60ffb0
2 :0x70ffb0
3 :0x80ffb0
4 :0x90ffb0
0x60ffb0 - 0x50ffb0 &#61; 0x100000 byte &#61; 1MB
那么这个小程序中线程最小堆栈大小为1MB. (对么?为什么呢?后面有验证)
将STACK_SIZE换成0, 结果和上面一样
将STACK_SIZE换成2, 结果变成2MB
以下是从MSDN中查到的
Generally, the reserve size is the default reserve size specified in theexecutable header. However, if the initially committed size specified by dwStackSize is larger than the default reserve size, the reserve size is this new commit size rounded up to the nearest multiple of 1 MB.
根据winnt.h中的 IMAGE_OPTIONAL_HEADER结构体
typedef struct _IMAGE_OPTIONAL_HEADER {
//
// Standard fields.
//
WORD Magic;
BYTE MajorLinkerVersion;
BYTE MinorLinkerVersion;
DWORD SizeOfCode;
DWORD SizeOfInitializedData;
DWORD SizeOfUninitializedData;
DWORD AddressOfEntryPoint;
DWORD BaseOfCode;
DWORD BaseOfData;
//
// NT additional fields.
//
DWORD ImageBase;
DWORD SectionAlignment;
DWORD FileAlignment;
WORD MajorOperatingSystemVersion;
WORD MinorOperatingSystemVersion;
WORD MajorImageVersion;
WORD MinorImageVersion;
WORD MajorSubsystemVersion;
WORD MinorSubsystemVersion;
DWORD Win32VersionValue;
DWORD SizeOfImage;
DWORD SizeOfHeaders;
DWORD CheckSum;
WORD Subsystem;
WORD DllCharacteristics;
DWORD SizeOfStackReserve;
DWORD SizeOfStackCommit;
DWORD SizeOfHeapReserve;
DWORD SizeOfHeapCommit;
DWORD LoaderFlags;
DWORD NumberOfRvaAndSizes;
IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
} IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32;
我推测,应该可以在链接期间指定栈大小
查看link.exe的参数
/STACK:reserve[,commit]
果然如此~~
看到网上有人问如何改变默认的线程堆栈大小,在MSDN中有答案:
The default size for the reserved and initially committed stack memory is specified in the executable file header. Thread or fiber creation fails if there is not enough memory to reserve or commit the number of bytes requested. To specify a different default stack size for all threads and fibers,use the STACKSIZE statement in the module definition (.def) file. For more information on these default sizes and how to change them, see the documentation included with your linker.
(模块定义 (.def) 文件为链接器提供有关被链接程序的导出、属性及其他方面的信息)
可见,默认线程堆栈大小在链接阶段可以由程序员指定
以上部分载自他人空间.
MSDN中有段话很重要:
To change the reserved stack size, set the dwCreationFlagsparameter ofCreateThreadorCreateRemoteThreadtoSTACK_SIZE_PARAM_IS_A_RESERVATIONand use thedwStackSizeparameter.
我用MSDN2001版查看的时候,它有注明STACK_SIZE_PARAM_IS_A_RESERVATION 适用于XP系统, 在MSDN2008版没注明了,我是在XP下测试的
下面是我改的测试代码:
代码