Methods for accessing member variables in MFC thread functions

Source: Internet
Author: User
Tags thread class

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.