2010. 4. 19. 22:33

Thread의 최대 생성 수는 얼마 일까?

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


많은 분들이 Thread And Thread pool 모델을 사용하여 C/S 프로그래밍을 구현을 합니다.

근데 한번 쯤 생각 해 보셨을 법한 것중 하나가 Thread의 Limit이 얼마 일까? 가 아닐까 합니다.

일단 소스로 보자면 이러 합니다. ( 참고한 글은 이곳입니다. )


#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

DWORD CALLBACK ThreadProc(void*)
{
Sleep(INFINITE);
return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
int i;
for (i = 0; i < 100000; i++) {
 DWORD id;
 HANDLE h = CreateThread(NULL, 0, ThreadProc, NULL, 0, &id);
 if (!h) break;
 CloseHandle(h);
}
printf("Created %d threads\n", i);

 int j;
for (j = 0; j < 100000; j++) {
 DWORD id2;
 HANDLE h2 = CreateThread(NULL, 1024, ThreadProc, NULL,
              STACK_SIZE_PARAM_IS_A_RESERVATION, &id2);

  if (!h2) break;
 CloseHandle(h2);
}
printf("Created %d threads\n", j);
return 0;
}

제 컴퓨터의 결과 값은 이러 합니다.

Created 2026 threads

2026 개의 Thread가 최대로 생성 가능한 갯수 인데요..왜 2026개 일까요??

이부분에 답은 MSDN에서 찾을수 있습니다. 

원문Link

... 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. The default stack reservation size used by the linker is 1 MB. To specify a different default stack reservation size for all threads and fibers, use the STACKSIZE statement in the module definition (.def) file.....

...PE Header에는 기본적으로 사용될 스택의 사이즈가 예약 되어 있고, 초기화시 Commit이 됩니다. 쓰레드와 피버는 생성시킬때 사용될 메모리 사이즈가 부족 할 시 생성이 실패 합니다. 1MB는 링커에 의해서 사용되는 기본 스택 사이즈 이며, 다른 기본 스택 사이즈를 쓰레드와 피버에 적용 시킬시 , 모듈 정의 파일(.def)에 STACKSIZE 란 선언문을 사용 하면 됩니다...

즉, 쓰레드 및 피버는 1MB의 스택 사이즈를 예약 한후 생성이 되며, 메모리가 충분치 못할 경우 생성에 실패를 한다고 합니다.

보통 User_Mode에서 사용되는 가상 메모리 주소의 한계는 2GB입니다. (링크원문)

즉 2048MB가 2G에 해당되지만, 실제적으로 코드가 및 힙등에 사용되는 메모리를 제하면 2048MB를 모두 사용할수는 없습니다.

그리 하여 유저 모드에서 Thread를 생성할때의 한계는 Thread * 1MB(Reserved Stack Size) 이므로 2000개 즈음이 됩니다.


추가로 참고할 링크
http://blogs.technet.com/markrussinovich/archive/2009/07/08/3261309.aspx
http://technet.microsoft.com/en-us/library/ms189334.aspx
http://blogs.msdn.com/oldnewthing/archive/2005/07/29/444912.aspx

2010/09/27일 추가.

http://blog.wouldbetheologian.com/2010/09/valid-reasons-for-using-threads.html

쓰레드를 왜 써야 하며, 어디에 써야 하는지 잘 설명한 글입니다. 참고 하시길 바랍니다.

많은 분들이 쓰레드의 양날의 검을 구체적으로 모르실때 한번 참고 하시면 괜찮을듯 합니다.

'관련자료' 카테고리의 다른 글

Huffman Coding  (0) 2010.05.03
BlowFish에 관해서.  (0) 2010.04.25
RSA 기반의 공개키 시스템.  (0) 2010.04.14
D-H 키 교환 방식에 관해서.  (0) 2010.04.12
Chart 12  (0) 2010.04.09