To start a thread with AfxBeginThread, there are two ways to define a thread's execution function:
1. Global function: UINT threadmessageboxadapter (LPVOID lParam);
2. Static member function: Static UINT threadmessageboxadapter (LPVOID lParam);
Our general experience is that the use of variables in a thread must be global, and member variables are defined as static to access member variables in thread functions.
This shows a way to access a member variable in a thread function:
This defines the thread class:
Class Thread
{
Public
Static UINT Threadmessageboxadapter (LPVOID lParam);
UINT Threadmessageboxproc ();
Private
CString Strthreadtext;
};
Implementation of thread functions:
UINT Thread::threadmessageboxadapter (LPVOID lParam)
{
ctestvectordlg* obj = (ctestvectordlg*) LParam;
return Obj->threadmessageboxproc ();
}
UINT Thread::threadmessageboxproc ()
{
CString Strthreadtext;
Strthreadtext.format (_t ("%s"), _t ("Thread adapter"));
AfxMessageBox (Strthreadtext);
return 0;
}
To start a thread using AfxBeginThread:
cwinthread* thread;
Thread = AfxBeginThread (Threadmessageboxadapter, this);
This way, when the thread starts, the message "Thread Adapter" pops up, stating that the member variable has been successfully accessed.