核心点:每个线程中只有一个T类型的线程特定数据,各个线程通过muduo::ThreadLocalSingleton<T>::instance()
的方式,获取各自的T类型的线程特定数据。(很巧妙!)
ThreadLocalSingleton< T >类
ThreadLocalSingleton.h
#ifndef MUDUO_BASE_THREADLOCALSINGLETON_H
#define MUDUO_BASE_THREADLOCALSINGLETON_H
#include <boost/noncopyable.hpp>
#include <assert.h>
#include <pthread.h>
namespace muduo
{
//核心点:各个线程通过muduo::ThreadLocalSingleton<T>::instance()的方式,获取T类型的线程特定数据。
template<typename T>
class ThreadLocalSingleton : boost::noncopyable
{
public:
static T& instance()//返回单例对象,不需要按照线程安全方式实现,__thread类型本身就是线程安全的
{
if (!t_value_)
{
t_value_ = new T();//重点
deleter_.set(t_value_);
}
return *t_value_;
}
static T* pointer()
{
return t_value_;
}
private:
static void destructor(void* obj)
{
assert(obj == t_value_);
typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1];
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);//类似key-value绑定
}
pthread_key_t pkey_;
};
static __thread T* t_value_;//线程特定数据的指针(指针类型是POD类型)
static Deleter deleter_;
};
template<typename T>
__thread T* ThreadLocalSingleton<T>::t_value_ = 0;
template<typename T>
typename ThreadLocalSingleton<T>::Deleter ThreadLocalSingleton<T>::deleter_;//第一个typename表示数据类型是类类型,然后这里会调用Deleter类的构造函数
}
#endif
测试
ThreadLocalSingleton_test.cc
#include <muduo/base/ThreadLocalSingleton.h>
#include <muduo/base/CurrentThread.h>
#include <muduo/base/Thread.h>
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
#include <stdio.h>
class Test : boost::noncopyable
{
public:
Test()
{
printf("tid=%d, constructing %p\n", muduo::CurrentThread::tid(), this);
}
~Test()
{
printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, name_.c_str());
}
const std::string& name() const { return name_; }
void setName(const std::string& n) { name_ = n; }
private:
std::string name_;
};
void threadFunc(const char* changeTo)
{
muduo::ThreadLocalSingleton<Test>::instance().setName(changeTo);
printf("tid=%d, %p name=%s\n",
muduo::CurrentThread::tid(),
&muduo::ThreadLocalSingleton<Test>::instance(),
muduo::ThreadLocalSingleton<Test>::instance().name().c_str());
// no need to manually delete it
// muduo::ThreadLocalSingleton<Test>::destroy();
}
int main()
{
muduo::ThreadLocalSingleton<Test>::instance().setName("main one");
muduo::Thread t1(boost::bind(threadFunc, "thread1"));
muduo::Thread t2(boost::bind(threadFunc, "thread2"));
t1.start();
t2.start();
t1.join();
printf("tid=%d, %p name=%s\n",
muduo::CurrentThread::tid(),
&muduo::ThreadLocalSingleton<Test>::instance(),
muduo::ThreadLocalSingleton<Test>::instance().name().c_str());
t2.join();
pthread_exit(0);
}
小结
ThreadLocalSingleton和Singleton<ThreadLocal< T >>实际上效果都是一样的,只是实现的方式不一样。