Windows 64 bit and stack size created by new thread is different
I hope this is the correct forum to ask this question.
I have a server application that creates a lot of threads (has to for now,
but this can change in the future).
To keep the VM size down, the application is linked with /STACK:65536, and
every thread that is created is done so with a specification of a 64K size
and the option STACK_SIZE_PARAM_IS_A_RESERVATION. This works in keeping the
amount of reserved memory down to approximately 64K for each new thread on
platforms such as WinXP x32 and Win2K3 Server x32.
On Win2K3 Server R2 x64, the amount of memory reserved for each new threads
is not 64K, but approximately 384K. On WinXP x64, it is similar.
Anyone have an idea as to why this happens, and better yet, a way of keeping
the reserve size down to what I have specified? Using beginthreadex() or
CreateThread() exhibits the same behaviour, so I don't see that as the issue.
Sample program to launch a specified number of threads and the then wait for
CTRL-C to terminate:
#include <windows.h>
#include <stdio.h>
BOOL fShutdown = FALSE;
static BOOL HandlerRoutine(DWORD dwControl)
{
dwControl = dwControl;
fShutdown = TRUE;
return TRUE;
}
void WINAPI thread(void *lpv)
{
printf("Started thread %u.\n", ((DWORD)lpv) + 1);
while (!fShutdown)
Sleep(1000);
}
int main(int argc, char *argv[])
{
DWORD i;
unsigned int dw;
DWORD nThreads;
HANDLE hThread;
if (argc < 2)
{
printf("Usage: threads <# of threads>\n");
printf("1 to 2000 is valid for threads\n");
return 1;
}
nThreads = atoi(argv[1]);
SetConsoleCtrlHandler((PHANDLER_ROUTINE)HandlerRoutine, TRUE);
for (i = 0; i < nThreads; i++)
{
if (0 == (hThread = (HANDLE)_beginthreadex(0, 0x10000, (unsigned int
(__stdcall *)(void *))thread, (LPVOID)i, STACK_SIZE_PARAM_IS_A_RESERVATION,
&dw)))
printf("Failed to create thread %u, gle=%u.\n", i + 1,
GetLastError());
else
CloseHandle(hThread);
}
while (!fShutdown)
Sleep(1000);
return 0;
}