What's the maximum number of threads in Windows Server 2003?

Does anyone know? And a bigger question is what happens when you encounter this maximum? Is this the same number with other Windows OSs such as Vista, XP etc.?


Solution 1:

First I would advise reading this: http://blogs.msdn.com/oldnewthing/archive/2007/03/01/1775759.aspx

then http://blogs.msdn.com/oldnewthing/archive/2005/07/29/444912.aspx

To summarise, the limitation is normally stack space (which must be in contiguous blocks) and since every thread consumes this scattered about you rapidly run out of contiguous blocks. On 64 bit machines and operating systems this is much less of a problem.

Mitigation strategies exist but will only go so far (and rely on you not using much stack per thread)

As a rough guide:

  • creating tens is almost certain to work
  • hundreds is probable on current server and desktop hardware but risky
  • thousands will almost certainly fail.

You likely shouldn't need to create more than ten anyway (and if you really do need to you should know this information already)

Solution 2:

The best answer I've heard when asking such questions is:

It doesn't matter, and if you find that it does matter, you need to rethink what you're doing so that it doesn't matter.

Solution 3:

Note that you should examine your design closely if you are concerned about hitting this limit!!!!!!!!

The answer to your "More Important Question" of what happens is OutOfMemoryException.

Not exactly a direct answer, but here's some code to find out the limit. It could be available memory dependent though. Would be interested in seeing other OS/cpu/mem results.

Feel free to edit and add your machine in:

  • Windows 7, VS2008, dual core, 2gb mem: 1,465 then crash with OutOfMemoryException

        int i = 0;
        try
        {
            while (true)
            {
                new Thread(new ThreadStart(() => Thread.Sleep(int.MaxValue))).Start();
                i++;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(i);
            Console.WriteLine(ex.ToString());
        }
    

Solution 4:

Do read the Raymond Chen blog postings that ShuggyCoUk's answer pointed to.

But pay special attention to this bit:

But the real question that is raised whenever somebody asks, "What's the maximum number of threads that a process can create?" is "Why are you creating so many threads that this even becomes an issue?"

The "one thread per client" model is well-known not to scale beyond a dozen clients or so. If you're going to be handling more than that many clients simultaneously, you should move to a model where instead of dedicating a thread to a client, you instead allocate an object. (Someday I'll muse on the duality between threads and objects.) Windows provides I/O completion ports and a thread pool to help you convert from a thread-based model to a work-item-based model.