Click to See Complete Forum and Search --> : Do threads have their own stack space?
John E
March 1st, 2004, 03:19 AM
I never really thought of this before but what happens to a program's stack pointer after it launches multiple threads?
Obviously the threads are time-sliced so they aren't literally happening simultaneously - but there's nothing to stop a function being called in thread 'B' while another function in thread 'A' is still executing. With a single stack this would presumably push new variables onto the stack which thread 'A' doesn't know about. How is this resolved? Does the OS take care of the stack pointer while switching between threads or does each thread get its own stack space :confused:
asivakumar
March 1st, 2004, 04:31 AM
The code segment is only shared apart from tht
The rest of segments like eg
data segment is not shared between thread
Andreas Masur
March 1st, 2004, 04:56 AM
[Moved thread]
Andreas Masur
March 1st, 2004, 04:58 AM
From MSDN:
A thread consists of a stack, the state of the CPU registers, and an entry in the execution list of the system scheduler. Each thread shares all of the process’s resources.
cvogt61457
March 1st, 2004, 01:59 PM
To expand on the quote that Andreas posted, each thread has its
own stack. The OS is responsible for switching to that thread's
stack when the thread is activated.
A thread may allocate resources (variables, objects, etc.) on its
stack. You can use these resources in other threads if desired.
Note: If you use variables in more than a single thread, you must
be careful that the data in the variable is properly protected so
that you multiple threads don't corrupt the data. This protection
and synchronization is the most difficult aspect of multi-threaded
programs and is where most programmers fail to properly protect
the data.
John E
March 1st, 2004, 02:07 PM
Thanks guys!
dimm_coder
March 2nd, 2004, 11:02 AM
Originally posted by John E
Obviously the threads are time-sliced so they aren't literally happening simultaneously ...
That happens if the code is running on machines with more that 1 processor (SMP).
But like it has been pointed out, each thread has its own stack.
codeguru.com
Copyright 2007 Jupitermedia Corporation All Rights Reserved.