2

Might sound like a silly question but I just wondered how many different stack areas there are in memory with say 4 CPU cores (if this really depends on the number of CPUs at all)?

To my knowledge at some point during boot before the execution of the first C function within the bootloader, somewhere in memory there'll be created an area reserved for a single stack. Since at this point (with only one running CPU core) there is only one single thread I guess only one single stack area will be created.

Then as soon as the other 3 CPUs are turned on, 3 other stacks are created. I guess every kernel thread will have it's own stack area and every user process and thread as well.

Is this naive assumption correct? Not sure if SO is the right place to post this question, but since it's STACKoverflow I guess it is. SU does not even have a proper stack tag.

JohnnyFromBF
  • 9,873
  • 10
  • 45
  • 59

1 Answers1

2

(I am assuming that by "stack area" you are not referring to a pool of memory from which many stacks for different threads of execution may be allocated. Instead, I am assuming that you the area of memory allocated for a specific stack.)

I don't mean for this answer to sound glib, but the short answer is that there are as many as necessary.

Now for the longer answer. Generally, in a multi-threaded system (which may or may not have multiple CPUs) there is at least one stack assigned per execution thread. OSes on which I have worked typically carve memory for the stack and the thread-control-block together so that they are adjacent. This 1:1 ratio of stack to thread offers much more flexibility to the user when writing multi-threaded code.

Things get a little more complicated if the system has user-space threads that make system calls into the kernel. From what I have seen, the user-thread generally switches to a new stack (located in kernel space) for as long as it is processing the system call. Some systems may have a small number of these system call stacks from which to choose (thereby limiting the number of user-threads that can make concurrent system calls), or there may be one system call stack per user-thread.

What about interrupts/exceptions? Again, this will vary according to the system. The interrupt might share the stack of the interrupted thread, or have its own stack.

If your system supports multiple CPUs, you can expect to have at least one thread per CPU. This would make the number of stacks a function of the number of threads, not the number of CPUs.

Hope this helps.

Sparky
  • 13,505
  • 4
  • 26
  • 27