15

This question is related with my previous question Thread overhead

Since Thread.Start doesn't claim memory for the thread to run, why it can throw OutOfMemoryException?

2
  • What are you doing in the thread?
    – musefan
    Apr 3, 2013 at 14:03
  • 1
    It doesn't matter what the thread is doing -- those things will throw their own OutOfMemoryExceptions -- they won't trickle back to thread.start. Jan 26, 2016 at 0:55

3 Answers 3

23

Here's part of the source code for starting up a managed thread in the CLR:

CExecutionEngine::SetupTLSForThread(pThread);
if (!pThread->InitThread(fInternal) ||
    !pThread->PrepareApartmentAndContext())
    ThrowOutOfMemory();
if (UnsafeTlsSetValue(gThreadTLSIndex, (VOID*)this) == 0)
{
    ThrowOutOfMemory();
}
if (UnsafeTlsSetValue(GetAppDomainTLSIndex(), (VOID*)m_pDomain) == 0)
{
    ThrowOutOfMemory();
}

Sure looks like it can throw out of memory in a number of situations; if the thread cannot be initialized, if the apartment or context cannot be prepared, or if the thread local storage cannot be allocated, then "out of memory" is thrown.

In my opinion this is a bad idea; I would prefer "out of memory" to be reserved for the situation of "I tried to allocate a new block of virtual memory and I couldn't find a block of the needed size." Throwing out of memory for things like there being no TLS slots available or thread initialization failing is just confusing.

4

Although the stack of the thread is claimed only when the thread actually starts, registering the thread for execution still takes some memory and thus can lead to an OutOfMemoryException.

0
0

I think you got something wrong. A thread DOES take memory in order to start. Every thread has its own stack, own stackpointer, etc. which memory must be reserved for. And if you happen not to have enough memory, an exception will be thrown.

2
  • You might want to read the answer on the linked question. It states that the stack is only claimed when the thread actually starts. Thread.Start doesn't do that. It just schedules the thread to be started. Apr 3, 2013 at 14:09
  • Possibly, but do you know exactly what is going on there?
    – bash.d
    Apr 3, 2013 at 14:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.