javac++multithreading

Stack behavior when adding new thread


What happens to stack when we create new thread? If it gets on the top of the stack, so how is it a thread?! If it doesn't get on the top of the thread, so how the program know where to continue it's job?


Solution

  • Each thread gets it's own stack. So if the initial thread creates a second thread, then this does not affect the stack of the first thread. And the second thread will have it's own stack. So in that process two independant stacks exist - one per thread. But each thread will only use it's own stack. The operating system sees both threads and stacks - and takes care that the proper stack is being set/used when switching from one thread to another.