Re: thread - structure
On Tue, 20 Jun 2006 10:51:28 -0500, "cdg" <anyone@anywhere.com> wrote:
Could anyone help me with the correct code to pass a structure to a
worker thread. I would prefer to pass the "this" pointer, but I am not sure
how to include it in a struct declaration or how to initialize it. But the
main problem I am having is how to write the code after the structure has
been passed to the worker thread. How do you access the individual variables
of the struct in the worker thread?
void CThreadTestDlg::OnStart()
{
struct ThreadStruct
{
HWND hWnd;
long NumA;
unsigned short NumB;
unsigned short NumC;
};
ThreadStruct* threadinputs = new ThreadStruct;
threadinputs-> hWnd=m_hWnd;
threadinputs-> NumA = Num1;
threadinputs-> NumB = Num2;
threadinputs-> NumC = Num3;
AfxBeginThread(Thread1, threadinputs);
}
UINT CThreadTestDlg::Thread1(LPVOID lParam)
{
***Struct Statements***
return 0;
}
First thing, you can't define the struct locally inside a function, because
the struct will not be usable outside that function. You should declare it
as a nested class, e.g.
// In .h file
class CThreadTestDlg
{
....
// No need to define it here, unless multiple .cpp files will use it.
struct ThreadStruct;
static UINT Thread1(LPVOID lParam);
};
// In .cpp file
struct CThreadTestDlg::ThreadStruct
{
HWND hWnd;
long NumA;
unsigned short NumB;
unsigned short NumC;
};
....
UINT CThreadTestDlg::Thread1(LPVOID lParam)
{
ThreadStruct* p = static_cast<ThreadStruct*>(lParam);
return 0;
}
*****
I'd suggest adding a ctor to ThreadStruct and have it perform the
initialization. To pass the this pointer, you would just add a
CThreadTestDlg* member to ThreadStruct, but note you should observe all the
usual caveats about sending messages between threads and post user-defined
messages to communicate with the dialog instead. For more information on
using CWinThread safely, see:
http://members.cox.net/doug_web/threads.htm
Hopefully I'll find time to update this document in the near future to
include some discussion of interthread SendMessage.
--
Doug Harrison
Visual C++ MVP