欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-30 12:17:03
muduo利用pthread_key_t实现ThreadLocal模板类. 具体代码如下所示: 代码除destructor均较为容易理解,故对此进行解释: PS: 如果您觉得我的文章对您有帮助,可以扫码领取下红包,谢谢! ......

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:

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

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