The general use of static functions as a thread callback function implementation, but always feel is not very smooth, change it, it is like destroying the encapsulation of the class, do not change it, access is really troublesome. So, what we're going to do today is let the member function of the class exist as a callback function for the thread, and a more specific structure used is
Union { void (*threadproc) (LPVOID pvparam); void (Student::*memberproc) (LPVOID pvparam);} Proc;
Union class, used to convert a class member method pointer to a normal function pointer
Here is a small plum, variable name to live to see it, the core idea is also reference other blog posts. Practice.
classstudent{ Public: Student () {M_handle=NULL; Name="Llil"; Age= -; } voidPrintinfo (LPVOID pvparam); voidstartUp (); Private: HANDLE m_handle; intAge ; stringname;}; Union {void( *ThreadProc) (LPVOID pvparam); void(Student::*Memberproc) (LPVOID pvparam);} Proc; voidStudent::p rintinfo (LPVOID pvparam) {student* PS = (Student *) Pvparam; while(true) {cout<<" Age"<<pS->age<<Endl; cout<<"name"<<pS->name<<Endl; Sleep ( -); }}voidStudent::startup () {Proc.memberproc= &student::p rintinfo; M_handle= CreateThread (NULL,0, Lpthread_start_routine (Proc.threadproc), This,0,0);}int_tmain (intARGC, _tchar*argv[]) {student S1; S1.startup (); System ("Pause"); _CrtDumpMemoryLeaks (); return 0;}
It is more important that you have to access the class members with pointers, or the runtime crashes if the compilation is not a problem. There are some issues such as memory not reachable. It's hard to find
Another way to do this is through a friend function.
classstudent{ Public: Student () {M_handle=NULL; Name="Llil" ; Age= - ; } friend UINT WINAPI printinfo (LPVOID pvparam); voidstartUp ();Private: HANDLE m_handle; intAge ; stringname;}; UINT WINAPI printinfo (LPVOID pvparam) {student* PS = (Student *) Pvparam; while(true) {cout<<" Age"<<pS-> age<<Endl; cout<<"name"<< Ps->name <<Endl; Sleep ( -); } return 0 ;}voidStudent:: StartUp () {M_handle= CreateThread (NULL,0, (Lpthread_start_routine) Printinfo, This,0,0);}int_tmain (intARGC, _tchar*argv []) {student S1; S1. StartUp (); System ("Pause"); _CrtDumpMemoryLeaks (); return 0 ;}
The member function of the class implements the thread's callback function