当前位置: 移动技术网 > IT编程>开发语言>C/C++ > muduo-ThreadLocal实现细节——阻止销毁未定义对象

muduo-ThreadLocal实现细节——阻止销毁未定义对象

2018年11月01日  | 移动技术网IT编程  | 我要评论

国产手机挡弹救命,丁建国,橙色八月

muduo利用pthread_key_t实现threadlocal模板类.

具体代码如下所示:

 1     template<typename t>
 2     class threadlocal : noncopyable
 3     {
 4     public:
 5         threadlocal()
 6         {
 7             mcheck(pthread_key_create(&pkey_, &threadlocal::destructor));
 8         }
 9 
10         ~threadlocal()
11         {
12             mcheck(pthread_key_delete(pkey_));
13         }
14 
15         t &value()
16         {
17             t *perthreadvalue = static_cast<t *>(pthread_getspecific(pkey_));
18             if (!perthreadvalue)
19             {
20                 t *newobj = new t();
21                 mcheck(pthread_setspecific(pkey_, newobj));
22                 perthreadvalue = newobj;
23             }
24             return *perthreadvalue;
25         }
26 
27     private:
28 
29         static void destructor(void *x)
30         {
31             t *obj = static_cast<t *>(x);
32             typedef char t_must_be_complete_type[sizeof(t) == 0 ? -1 : 1];
33             t_must_be_complete_type dummy;
34             (void) dummy;
35             delete obj;
36         }
37 
38     private:
39         pthread_key_t pkey_;
40     };

 

代码除destructor均较为容易理解,故对此进行解释:

 1 static void destructor(void *x)
 2 {
 3     t *obj = static_cast<t *>(x);   
 4         //对于只声明,未进行具体定义类型,例如a,sizeof(a)结果为0 
 5         //利用此特性,若t是未定义类型,则t_must_be_complete_type在编译期间会报错
 6     typedef char t_must_be_complete_type[sizeof(t) == 0 ? -1 : 1];
 7         //消除unused-local-typedefs编译错误提示
 8     t_must_be_complete_type dummy; 
 9         //消除wno-unused-parameter编译错误提示  
10     (void) dummy;
11     delete obj;
12 }

 

ps:

如果您觉得我的文章对您有帮助,可以扫码领取下红包,谢谢!

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网