Class members as thread entry functions

 

Declare class member functions as friend functions. The function implementation is implemented outside the class. It must be this way. Otherwise, using other strange and rare methods to obtain the address of the class member function will cause unpredictable consequences.

The context parameter of the thread entry function passes the this pointer in order to access the protected and private members of the class.

 

Here is sample code:

1  // ThreadMember.cpp : Defines the entry point for the console application. 
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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324992377&siteId=291194637