类成员作为线程入口函数
把类成员函数声明为友元函数。函数实现在类外实现。一定要这样。不然用其他奇葩少见的方法获取类成员函数的地址,会造成不可预料的后果。
线程入口函数的上下文参数传入this指针,以便访问类的proteted和private成员。
以下是示例代码:
1 //ThreadMember.cpp : 定义控制台应用程序的入口点。 2 3 #include"stdafx.h" 4 5 #include<string> 6 7 #include<Windows.h> 8 9 #include<iostream> 10 11 using namespace std; 12 13 class student 14 15 { 16 17 public: 18 19 student() 20 21 { 22 23 m_handle = NULL; 24 25 name = "Member fun is ThreadFun."; 26 27 age = 13; 28 29 } 30 31 friend UINT WINAPIprintInfo(LPVOID pvParam); 32 33 void startUp(); 34 35 36 37 private: 38 39 HANDLE m_handle; 40 41 int age; 42 43 string name; 44 45 }; 46 47 48 49 UINT WINAPI printInfo (LPVOID pvParam) 50 51 { 52 53 student * pS = (student * ) pvParam; 54 55 while(true ){ 56 57 cout <<"age"<<pS-> age<<endl ; 58 59 cout <<"name"<<pS->name <<endl; 60 61 Sleep (2000); 62 63 } 64 65 return 0 ; 66 67 } 68 69 70 71 void student::startUp() 72 73 { 74 75 m_handle =CreateThread(NULL,0,LPTHREAD_START_ROUTINE(printInfo),this,0,0); 76 77 } 78 79 80 81 int _tmain(int argc, _TCHAR*argv[]) 82 83 { 84 85 student s1; 86 87 s1.startUp(); 88 89 system("pause"); 90 91 _CrtDumpMemoryLeaks(); 92 93 return 0; 94 95 }
references:
https://blog.csdn.net/xiaominggunchuqu/article/details/54342064