What if we run out of stack space in C# or Python?

Posted by dotneteer on ASP.net Weblogs See other posts from ASP.net Weblogs or by dotneteer
Published on Thu, 05 Jul 2012 05:16:00 GMT Indexed on 2012/07/05 9:16 UTC
Read the original article Hit count: 299

Filed under:
|

Supposing we are running a recursive algorithm on a very large data set that requires, say, 1 million recursive calls. Normally, one would solve such a large problem by converting recursion to a loop and a stack, but what if we do not want to or cannot rewrite the algorithm?

Python has the sys.setrecursionlimit(int) method to set the number of recursions. However, this is only part of the story; the program can still run our of stack space. C# does not have a equivalent method.

Fortunately, both C# and Python have option to set the stack space when creating a thread. In C#, there is an overloaded constructor for the Thread class that accepts a parameter for the stack size:

Thread t = new Thread(work, stackSize);

In Python, we can set the stack size by calling:

threading.stack_size(67108864)

We can then run our work under a new thread with increased stack size.

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about c#