ThreadLocalSingle (19)

本文介绍了一种线程本地单例模式的实现方法,利用 C++ 的 pthread 和模板特性来确保每个线程都有自己的单例实例。通过 ThreadLocalSingleton 类的定义,详细解释了其实现原理,并提供了一个具体的测试案例。

ThreadLocalSingle class UML



源程序:

// 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 <boost/noncopyable.hpp>
#include <assert.h>
#include <pthread.h>
/**

线程本地单例封装
---------------------------
-ponce_:pthread_once_t
-value:T*
----------------------
+instance():T&
<<create>>-Singleton()
<<destroy>>-Singleton()
-init():void
-destroy():void
---------------------------
***/

namespace muduo
{

//使用模板
template<typename T>
class ThreadLocalSingleton : boost::noncopyable //不可复制的
{
 public:

  static T& instance()
  {
    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_);
    //T_must_be_complete_type : 完全类型
    // Thread a; 
    // a *p  ; //p这种类型就不是完全类型
    typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1];
    //
    delete t_value_;
    t_value_ = 0;
  }

/**
Deleter 主要是用来使ThreadLocalSingleton::destructor作为pkey_的虚构回调函数
Deleter 只是虚构时只是pthread_key_delete(pkey_)而已
**/
  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 修饰的变量一定是全局的或者静态的
  static Deleter deleter_;      //消费实际数据函数
};

template<typename T>
__thread T* ThreadLocalSingleton<T>::t_value_ = 0;

template<typename T>
typename ThreadLocalSingleton<T>::Deleter ThreadLocalSingleton<T>::deleter_;

}
#endif


测试程序

#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)
{
  printf("tid=%d, %p name=%s\n",
         muduo::CurrentThread::tid(),
         &muduo::ThreadLocalSingleton<Test>::instance(),
         muduo::ThreadLocalSingleton<Test>::instance().name().c_str());
  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);
}


程序输出

[root@localhost bin]# ./threadlocalsingleton_test 
tid=2183, Obj address  0x89b4028, function Test 
tid=2184, Obj address  0xb6c00468, function Test 
tid=2184, obj address 0xb6c00468 name=
tid=2184, 0xb6c00468 name=thread1
tid=2184, destructing 0xb6c00468 thread1
tid=2183, 0x89b4028 name=main one
tid=2185, Obj address  0xb6c00468, function Test 
tid=2185, obj address 0xb6c00468 name=
tid=2185, 0xb6c00468 name=thread2
tid=2185, destructing 0xb6c00468 thread2
tid=2183, destructing 0x89b4028 main one
[root@localhost bin]#



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值