views:

58

answers:

4

What's the policy for a thread to have a stack and a process to have a stack.

If we have 10 process, how many stacks we have, 10?

If we have 10 threads under one process, how many stacks we have, 1? All the thread shared the same stack?

Thanks!

A: 

Each process has its own stack. Thus N (single threaded) processes have N stacks.

Each thread has its own stack. Thus a process with N threads has N stacks.

janneb
-1, a process doesn't have a stack, only a thread. A process does have at least one thread.
Hans Passant
@nobugz, that is a needless -1. He specifically says in the answer that *single-threaded* processes have one stack each.
Mike Daniels
+1  A: 

One stack per thread. 5 processes with 2 threads each equals 10 stacks.

Christian Madsen
+1  A: 

Thread -> context of execution -> requires its own resources -> stack of its own.

jldupont
so there is no situation they share a stack?
skydoor
not in the systems I happen to know - or else, why incur the additional overhead of trying to delineate the call-stack between threads? Seems like an unnecessary overhead to me.
jldupont
+2  A: 

If you think about what the stack is, it doesn't make sense to share a stack.

Remember that this is a call stack not the data structure. As your instruction pointer (indicating the instruction to execute) moves through your program, it will encounter function calls which push the current context (local variables, IP before call) onto the stack before jumping to the called function. That function uses the top of the stack for its local variables, etc and when it's done the stack gets popped leaving the local variables for your original function on the top, and restoring the IP to just after the function call.

If two threads had the same stack, they would be sharing context, but they could conceivably have different IPs. If one of the threads called a function, the stack would no longer make sense for the other thread (which is still in the original function). If the IPs are synchronised, you haven't got two distinct threads - you're just doing everything twice.

So as others have said: One stack per thread, per process.

Draemon