C ++ syntax to achieve their own small mind --- Thread class

Thread class to achieve their own
1  // Embodiment 1: Use of static class function to do the conversion, with this pointer 
2  class the Thread
 . 3  {
 . 4  Private :
 . 5      pthread_t ID;
 . 6      
. 7      static  void * start_thread ( void * Arg)
 . 8      {
 . 9          the Thread Thread * = (the Thread * ) Arg;
 10          the Thread-> RUN ();
 . 11      }
 12 is  
13 is  public :
 14      
15      Virtual  void RUN ()
 16      {
 . 17          COUT << "success" <<endl;
18     }
19     
20     virtual void start()
21     {
22         pthread_create(&id, NULL, start_thread, (void *)this);//传入this指针是关键
23     }
24 }; 
25 
26 class MyThead: public Thread
27 {
28 public:
29     virtual void run()
30     {
31         cout << "MyThead::run()" << endl;
32     }
33 };
34 
35 
36 int main()
37 {
38     MyThead t;
39     t.start();
40     
41     sleep(2);
42     
43     return 0;
44 }

 

1  // Mode 2: Direct use of casts, because this-> xxx () is equivalent to xxx (this) essentially
 2  // embodiment 2 is more secure than 1 time, since no static 
. 3  class the Thread
 . 4  {
 . 5  Private :
 . 6      pthread_t ID;
 . 7      
. 8      void * threadFunc ( void * Arg)
 . 9      {
 10          the this -> RUN ();
 . 11      }
 12 is  
13 is  public :
 14      
15      typedef void * (the FUNC *) ( void * );
 16      
. 17      Virtual void RUN ()
 18 is      {
 . 19          COUT << " Success " << endl;
 20 is      }
 21 is      
22 is      Virtual  void Start ()
 23 is      {
 24          the FUNC = the callback (the FUNC) & the Thread :: threadFunc;
 25          pthread_create (& ID, NULL, the callback, this ); // where this is to be passed, and arg callback unavailable because of NULL 
26 is      }
 27  }; 
 28  
29  class MyThead1: public the Thread
 30  {
 31 is public:
32     virtual void run()
33     {
34         sleep(1);
35         cout << "MyThead1::run()" << endl;
36         
37     }
38 };
39 
40 class MyThead2: public Thread
41 {
42 public:
43     virtual void run()
44     {
45         cout << "MyThead2::run()" << endl;
46     }
47 };
48 
49 int main()
50 {
51     MyThead1 t1;
52     t1.start();
53     
54     MyThead2 t2;
55     t2.start();
56     
57     sleep(2);
58     
59     return 0;
60 }

 

Guess you like

Origin www.cnblogs.com/chusiyong/p/11315734.html