muduo库源码学习(base)ThreadLocalSingleton
来源:互联网 发布:网络电玩城捕鱼游戏 编辑:程序博客网 时间:2024/06/05 13:01
// Use of this source code is governed by a BSD-style license// that can be found in the License file.//// Author: Shuo Chen (chenshuo at chenshuo dot com)#ifndef MUDUO_BASE_THREADLOCALSINGLETON_H#define MUDUO_BASE_THREADLOCALSINGLETON_H#include <muduo/base/noncopyable.h>#include <assert.h>#include <pthread.h>namespace muduo{template<typename T>class ThreadLocalSingleton : noncopyable//线程局部的单例,也就是每个线程一个T。static __thread T* t_value_;{ public: static T& instance() { if (!t_value_) { t_value_ = new T(); deleter_.set(t_value_);//内存交给deleter释放 } return *t_value_; } static T* pointer() { return t_value_; } private: ThreadLocalSingleton(); ~ThreadLocalSingleton(); static void destructor(void* obj) { assert(obj == t_value_); typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1]; T_must_be_complete_type dummy; (void) dummy; delete t_value_; t_value_ = 0; } class Deleter { public: Deleter() { pthread_key_create(&pkey_, &ThreadLocalSingleton::destructor); } ~Deleter() { pthread_key_delete(pkey_); } void set(T* newObj) { assert(pthread_getspecific(pkey_) == NULL); pthread_setspecific(pkey_, newObj); } pthread_key_t pkey_; }; static __thread T* t_value_;//__thread无法调用class的析构 static Deleter deleter_;//wow!只有一个Deleter,程序结束时,它析构自己时通知系统执行destructor,一次性删除所有内存};template<typename T>__thread T* ThreadLocalSingleton<T>::t_value_ = 0;template<typename T>typename ThreadLocalSingleton<T>::Deleter ThreadLocalSingleton<T>::deleter_;}#endif
阅读全文
0 0
- muduo库源码学习(base)ThreadLocalSingleton
- muduo库源码学习(base)Atomic
- muduo库源码学习(base)AsyncLogging
- muduo库源码学习(base)Condition
- muduo库源码学习(base)CountDownLatch
- muduo库源码学习(base)Date
- muduo库源码学习(base)Exception
- muduo库源码学习(base)FileUtil
- muduo库源码学习(base)mutex
- muduo库源码学习(base)singleton
- muduo库源码学习(base)ThreadLocal
- muduo库源码学习(base):Logfile
- muduo库源码学习(base):LogStream
- muduo库源码学习(base):WeakCallback
- muduo库的ThreadLocalSingleton类剖析
- muduo库源码学习(base)BlockingQueue和BoundBlockingQueue
- muduo库源码学习(base)Thread和CurrentThread
- muduo网络库学习之ThreadLocal<T> 类、ThreadLocalSingleton<T>类封装知识点
- One Person Game ZOJ
- 改写一个sql server 的过程,增加参数,屡试多次才成功
- java程序运行时对象是怎么进行放置安排? 内存是如何分配的呢?
- 超级玛丽输出
- 获取时间
- muduo库源码学习(base)ThreadLocalSingleton
- switch开关语句
- HDU-2010(水仙花数)
- npm ERR!errno -4048
- 把pinpoint编译环境做成Docker镜像文件
- vue开发:vue引入echarts
- Spring Boot学习之旅:(十一)模版引擎-jsp
- Docker下,极速体验pinpoint1.6.3
- 【plan】noip冲刺计划