C++语法小记—自己实现Thread类

自己实现Thread类
 1 //方式1:使用类的static函数做转换,配合this指针
 2 class Thread
 3 {
 4 private:
 5     pthread_t id;
 6     
 7     static void * start_thread(void *arg)
 8     {
 9         Thread* thread = (Thread*)arg;
10         thread->run();
11     }
12 
13 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 //方式2:直接使用强制类型转换,因为this->xxx() 本质上等同于 xxx(this)
 2 //方式2比当时1更安全,因为没有使用static
 3 class Thread
 4 {
 5 private:
 6     pthread_t id;
 7     
 8     void* threadFunc(void* arg)
 9     {
10         this->run();
11     }
12 
13 public:
14     
15     typedef void* (*FUNC)(void*);
16     
17     virtual void run()
18     {
19         cout << "success" <<endl;
20     }
21     
22     virtual void start()
23     {
24         FUNC callback = (FUNC)&Thread::threadFunc;
25         pthread_create(&id, NULL, callback, this); //此处传入this是必须的,且在callback中arg不可用,因为为NULL
26     }
27 }; 
28 
29 class MyThead1: public Thread
30 {
31 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 }

 

原文链接: https://www.cnblogs.com/chusiyong/p/11315734.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++语法小记---自己实现Thread类

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/300456

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午9:27
下一篇 2023年2月15日 下午9:27

相关推荐