To start a thread with AfxBeginThread, there are two ways to define a thread's execution function:
Global function: UINT threadmessageboxadapter (LPVOID lParam);
Static member function: Static UINT threadmessageboxadapter (LPVOID lParam);
In the case of thread function global functions, variables used in threads must be global variables, dialog class member variables cannot be used, member variables are defined as static, and member variables can be accessed in a threaded function.
If the thread function is a static member function, then only class static member variables can be used.
Here is a way to access member variables in a thread function:
The thread class is defined here:
Class Thread
{
Public
Static UINT Threadmessageboxadapter (LPVOID lParam);//thread function, static member function
UINT Threadmessageboxproc ();//class member function
Private
CString Strthreadtext;
};
The implementation of the thread function:
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 was successfully accessed.