Click to See Complete Forum and Search --> : Variable goes out of scope in the child thread when parent thread returns


hanhao
April 10th, 2004, 10:21 AM
ok guys,
a quick newbie question:

how do i pass a variable into a thread when i still need that variable AFTER the parent thread returns. after hours of experimenting, i found the problem is when the parent thread returns, the variable in the child thread (formally passed by the parent thread) goes out of scope and disappears....

A few ideas i thought of

1) use static ?? i am now too sure on this

2) use a gobal variable?? i think it still goes out of scope too
anyway this is not very elegant method

3) anything???


in summary:
- a user interface thread starts a worker thread
- user interface thread returns so that the program doesnt freeze
- worker thread still needs to work around with the variable
<-- problem with the retaining of the variable when user interface thread goes out of scope


using
- visual c++ 6.0
- win98SE
- API, dont know much about MFC till i learn more on the basic APIs that make up MFC

Yves M
April 10th, 2004, 11:07 AM
Use a pointer to memory dynamically allocated with new. Then you can destroy it whenever it's not needed anymore and you can keep it as long as you like.

hanhao
April 12th, 2004, 02:36 AM
thnx for your valuable suggestion.
This is what i did:

char *thread_buffer;
thread_buffer = new char[];
thread_buffer = (*(start_thread_parm*)thread_parm).comd; // dynamically allocating the variable as suggested
SetEvent((*(start_thread_parm*)thread_parm).continue_broadcast_handle); // tells the parent thread that i have finished copying the parmeter to the child thread and it's ok to continue to return


This is the class of "start_thread_parm" summarized

class start_thread_parm{
public:
{
char *comd;
HANDLE continue_broadcast_handle;
}



is this the way to do it?
i keep getting the same problem when the parent thread returns, ie. the variable goes out of scope when the parent thread returns.
thread_buffer becomes empty after the line "SetEvent((*(start_thread_parm*)thread_parm).continue_broadcast_handle); "

I am doing something wrong here. any help plz?

Andreas Masur
April 12th, 2004, 05:46 AM
[Moved thread]

Andreas Masur
April 12th, 2004, 05:49 AM
Well...there are many information missing:

Where does 'thread_parm' gets allocated?
Where does 'thread_parm.comd' gets allocated?
How is the thread created?
How do you pass 'thread_parm'?
How do you cast them back inside the thread?
...

You need to dynamically allocate the data that you are passing to the thread...in other words, if 'start_thread_parm' is the class you want to pass to the thread, then you need to allocate one instance of that class dynamically...