一般都是用靜態函數作為線程的回調函數實現,但是總是感覺不是很順暢,更改吧,就好像破壞了類的封裝性,不改吧,訪問實在是麻煩。所以,今天要做的就是讓類的成員函數作為線程的回調函數存在,其中使用的一個比較特殊的結構就是
union { void ( *ThreadProc)(LPVOID pvParam); void ( student::*MemberProc)(LPVOID pvParam); } Proc;
聯合類,用於轉換類成員方法指針到普通函數指針
下面是一個小李子,變量名 就湊活看吧,核心思想也是參考其他博文。練習下。
class student { public: student() { m_handle = NULL; name = "llil"; age = 13; } void printInfo(LPVOID pvParam); void startUp(); private: HANDLE m_handle; int age; string name; }; union { void ( *ThreadProc)(LPVOID pvParam); void ( student::*MemberProc)(LPVOID pvParam); } Proc; void student::printInfo(LPVOID pvParam) { student * pS = (student * )pvParam; while(true){ cout<<"age" <<pS->age<<endl; cout<<"name"<<pS->name<<endl; Sleep(2000); } } void student::startUp() { Proc.MemberProc = &student::printInfo; m_handle = CreateThread(NULL,0,LPTHREAD_START_ROUTINE(Proc.ThreadProc),this,0,0); } int _tmain(int argc, _TCHAR* argv[]) { student s1; s1.startUp(); system("pause"); _CrtDumpMemoryLeaks(); return 0; }
其中比較重要的就是必須要以 指針訪問 類成員,否則雖然編譯沒問題,但是運行時會崩潰。出現內存無法訪問等一些問題。很難發現
還有一種方法就是通過友元函數實現。
class student { public: student () { m_handle = NULL; name = "llil" ; age = 13 ; } friend UINT WINAPI printInfo( LPVOID pvParam); void startUp(); private: HANDLE m_handle ; int age; string name ; }; UINT WINAPI printInfo (LPVOID pvParam) { student * pS = (student * ) pvParam; while(true ){ cout <<"age" <<pS-> age<<endl ; cout <<"name"<< pS->name <<endl; Sleep (2000); } return 0 ; } void student:: startUp() { m_handle = CreateThread( NULL,0 ,(LPTHREAD_START_ROUTINE) printInfo,this ,0, 0); } int _tmain( int argc, _TCHAR* argv []) { student s1 ; s1 .startUp(); system ("pause"); _CrtDumpMemoryLeaks (); return 0 ; }