How a thread function in C + + accesses a member variable in a class

Source: Internet
Author: User

1. How to define thread functions in C + +

There are two ways: a. Defines a thread function as a global function B. Static member functions that define a thread function as a class

2. How a thread function in C + + accesses a member variable in a class

Describes the static members of a class for thread functions. If you are a static data member, you can certainly access it directly, but if you want to access non-static data members, direct access is not possible. If you want to access and manipulate a non-static member variable for a class in a thread function, you can use the thread function as an adapter to invoke a Non-static member function of the class in the adapter. For example:

Class CMyClass
{
Public
void TestFunc ();
static int ThreadFunc (LPVOID pparam);//Adapter
Protected
int threadfunckernal ();//Kernal
}

void Cmyclass::testfunc ()
{
AfxBeginThread (Treadfunc, this);
}

Thread function Adapter
int Cmyclass::threadfunc (LPVOID pparam)
{
CMyClass *pobj = (CMyClass *) Pparam;
return pobj->threadfunckernal ();

}

Thread function Kernal
int cmyclass::threadfunckernal ()
{
while (1)
{
My thread
To control class Non-static member
}
return 0;
}

Related Article

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.