воскресенье, 7 февраля 2010 г.

.NET threads and stack memory

Normally when an unmanaged thread is created 1 MB of virtual address space is reserved and 4 KB (a page) is committed for its stack. Reserved here is an important word, because reservation allocates no physical storage but only well.. reserves a range of virtual memory.  It guaranties continuousness of the memory required for threads’ stacks. Allocation of the real storage (committing) happens as the stack grows, page by page. 
But as address space in a process is usually limited by 2 GB  the more threads you create the less virtual address space is left. For example, a thousand of threads can consume a half of the available  virtual memory of the process. 
But recently I have found that the things are different in the managed world. When a managed thread created  1 MB of memory is reserved and committed for its stack before it starts. There is no difference between a managed thread and an unmanaged one regarding virtual memory space consuming but the early committing  brings the whole system closer to the commit limit which is “the sum of physical memory and the sizes of the paging files”.
It is one more reason not to create threads if you can. Use ThreadPool, Tasks or  async IO instead.

You can read more about the reasons behind the CLR team’s decision,
what Windows memory limits are and how  Processes and Threads consume memory.

1 комментарий: