Quick Question Regarding Threads

closed account (zb0S216C)
When creating a thread with _beginthread( ), are variables created on the threads' stack or the programs' stack? Here's a sample piece of code. This will show you what I mean:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <process.h>

void Dummy_function( void *Args )
{
    int iDummy_var_one( 10 ); 
    // Is iDummy_var_one created on the threads'
    // stack, or the programs' stack?
    return;
}

int main( )
{
    _beginthread( &Dummy_function, 0, NULL );
        int iDummy_var_two( 10 );
        // Is iDummy_var_two created on the threads'
        // stack, or the programs' stack?
    _endthread( );

    return 0;


Apologizes if I haven't explained myself properly, but I don't how to explain it.
Every thread has it's own stack.
Wouldn't work otherwise.
Variables inside functions are duplicated so each function call has their own copies. Global variables, on the other hand, are not duplicated and can be shared between threads. This is where thread synchronization comes into play, so you don't corrupt the data.
closed account (zb0S216C)
caligulaminus wrote:
Every thread has it's own stack.

I know that. The 2nd parameter of _beginthread( ) is the size of the stack. If zero is passed, a default size of 1024 bytes( 1MB ) is used.

I understand where you come from WebJose, but that still doesn't answer my question.

Note: For this I'm referring to my above example. Dummy_function( ) is called by _beginthread( ). Is the local variable, iDummy_var_one within Dummy_function( ), allocated on the threads' stack or the programs stack?
Last edited on
Ah, I see. To be honest, I am not 100%. I would say it is the thread's stack. But wait or google for a more authoritative answer.
What you call the "program" is also just another thread.
Local -> on thread's stack.
What about globals? What stack is that one? I barely know anything about this subject, so I'm interested as well.
Framework wrote:
Note: For this I'm referring to my above example. Dummy_function( ) is called by _beginthread( ). Is the local variable, iDummy_var_one within Dummy_function( ), allocated on the threads' stack or the programs stack?


_beginthread does not call Dummy_function( ).

closed account (zb0S216C)
guestgulkan wrote:
_beginthread does not call Dummy_function( ).

So what is the purpose of argument 1 of _beginthread( )? If _beginthread( ) doesn't call the function passed in argument 1, what does it do with it?
It goes off and speak with what ever OS services that deals with threads and if thread is successfully setup/started it returns with the thread handle.

@webJose
Globals are not on the stack.
They reside in the data segment of your exe.
Cool. Thanks!
Topic archived. No new replies allowed.