Structure as paramater in AfxBeginThread

Mar 19, 2012 at 4:37pm
Good evening!

I try to pass a structure as parameter:

Global structure:
1
2
3
4
struct ThreadParams{
    HWND window;
    LIB::ServiceContainer* mrt;
};


In the main thread:
1
2
3
4
5
6
ThreadParams threadparams;
threadparams.window = (HWND) GetSafeHwnd();
threadparams.mrt = m_rt;

CWinThread* pthread1;
pthread1 = (CWinThread*) AfxBeginThread(Thread1,(LPVOID)&threadparams,THREAD_PRIORITY_NORMAL,0,0,0);


Outside the class:
1
2
3
4
5
6
7
8
9
10
UINT Thread1(LPVOID lp)
{
	ThreadParams* threadparams = (ThreadParams*) lp;
	
	HWND hmainWindow = threadparams->window; 
	LIB::ServiceContainer* m_rt = threadparams->mrt;

....

}


Although it compiles fine, I get an error on rutime (it is an unexpected error) and I guess that I mess up with the pointer m_rt. Do you see any obvious mistakes?

Thanks a lot in advance.
Mar 19, 2012 at 6:08pm
You must always handle memory that you are sure will live throughout the course of the new thread. This means that you must not use the stack for thread parameters because the thread might try to access the data once it has gone out of scope.

You should do:

1
2
3
4
5
6
ThreadParams *ptp = new Threadparams();
ptp->window = (HWND)GetSafeHwnd();
ptp->mrt = m_rt;
//Now use ptp as argument for the thread.
//Since you allocated in the heap, the data will be available until it is deleted.
//Make the thread delete this memory. 
Mar 19, 2012 at 6:10pm
threadparams in the main thread looks like it's a local variable to some function. The address of that local is passed to Thread1. But I bet the main thread returns from that function, which destroys the variable that was passed to Thread1, but Thread1 continues to refer to it.

You should consider allocating threadparams from the heap.
Mar 20, 2012 at 11:38am
It worked webJose, thank you very much. I understood your point.

Concerning your last notice
"//Make the thread delete this memory."
could you please point it out how may I delete that memory?

Thanks again

Mar 20, 2012 at 11:49am
Delete it in the thread function when the thread terminates (or when it's otherwise done with it).
Mar 20, 2012 at 12:37pm
The main thread allocated RAM using the new operator. To avoid a memory leak, this must be deleted once it is not used. Typically, the new thread does this when the data is no longer needed.

1
2
3
4
5
6
7
8
9
10
11
//This is the new thread's code:
UINT Thread1(LPVOID lp)
{
    //Reinterpret the data.
    ThreadParams *data = reinterpret_cast<ThreadParams*>(lp);
    //Work.
    ...
    //Ok, data no longer needed.  Delete the data through the proper pointer.
    delete data;
    //Don't delete using the pointer variable 'lp' because you want proper destruction.
}
Topic archived. No new replies allowed.