Multithreading: what’s the stack for?

In the last post, we’ve seen that one of the overloads used for creating a thread receives a parameter that lets you define the maximum size of the stack. Before going into details about those methods, I think it would be great to understand what it is and why we need it. A stack is just a contiguous region of memory that grows downward and that is used for several operations. Here are several examples:

  • allocate local variables;
  • passing parameter values to methods;
  • pass return values back.

As you can see (from the previous points), the stack is heavily used by compilers and generally you don’t have much interaction with it. If you’re thinking about .NET, then you probably already know that value types are allocated on the stack (though this is just a detail and you shouldn’t really care about it). Notice that you can also use the stackalloc keyword  for forcing stack allocation of a local variable.

It’s important to understand that whenever you create a thread, you’ll get a stack that is associated to that thread. If you choose the overload that doesn’t receive a size, then you’ll end up getting the default stack size: 1MB. Notice that this default value is also used for the main thread (which is automatically created for you when you start a process). If this size is not enough for your main thread, then you’ll have to tweak the default values in the PE. In managed code, you’ll probably end up using the editbin.exe app. Whenever you exceed this value, you end up getting a stack overflow and there’s not much you can do about it…

Joe Duffy’s excellent book goes into heavy details about the stack and is recommended reading for everyone who wants to understand this stuff (I’ve recommended his book several times and I’ll keep recommending it because it is my main influence in this field!).

Going back to important stack details, you’ve probably noticed that, since the stack isn’t shared,you might use it for storing “local” values without worrying with data synchronization. When you explicitly access the stack for this kind of action,we say that we’re using the thread local storage for saving values (again, that aren’t *shared* by the threads). Managed code lets you access this storage in two ways, but I’ll leave that for the next post in the series.

And that’s it…Keep tuned for more on multithreading…


~ by Luis Abreu on May 4, 2009.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: