views:

16

answers:

2

Hello,

I want to understand how is the memory for the stacks of the user level threads kept in memory. I think that all the stacks would begin at a page boundary... Am I right?? How does the user level thread library ensures that the stack for a certain thread wont grow and overlap with the contiguous page boundary stack of the other thread, since all the stack pages will be contiguous...

A: 

These are all implementation details and vary from system to system. What are you trying to accomplish?

Jonathan Grynspan
This was a general doubt... not trying to accomplish something specific... but still lets say linux user level thread library... on a broader perspective how will the memory for the stacks of multiple threads be kept in memory...
g__k
Your question cannot be answered with the information provided. This is an extremely implementation-dependent question, and without a specific target in mind (CPU architecture, OS version, calling convention, threading model) there is no answer.
Jonathan Grynspan
A: 

IF you insist on contiguous stacks, then yes, you can have a collision between stacks allocated for separate threads. This is more likely on a machine with a small virtual space than a large one, and more likely when some stack can become arbitrarily big.

Most common OSes (Windows, Linux) make the assumption that thread stacks can't be very big (e.g., 1-10Mb), and that you can't have a lot of threads (maybe hundreds) for a single process. In this case, you don't really have a problem if you know how many threads you need, and how big each stack can get, before your computation states. In this case, you can precompute where put all the thread stacks so they all fit, with worst-case demands per stack.

And this works .... pretty well. However, if the demand for a stack can be arbitrarily large, or you don't know how many stacks in advance, then preallocation doesn't work. And this does cause people using these OSes trouble.

See http://stackoverflow.com/questions/3217521/why-are-stack-overflows-still-a-problem for a discussion of this problem. You can read my response as to how to avoid the problem, too. (Hint: no limited size stacks!).

Ira Baxter