muduo源码分析3——TSD

1 什么是tsd

因为全局变量在所有线程中是共享的,如何才能拥有只在单个线程中共享的全局数据呢?这就需要tsd了。
可能会有疑问,这玩意到底有啥用,在线程中定义一个变量,其内部函数不也能使用吗?但是其不是全局的,需要传入到函数。

  1. 线程私有数据采用了一种被称为一键多值的技术,即一个键对应多个数值,当需要使用该值时,通过key获取实际数据。
  2. key一旦被创建,所有线程都可以访问它,但各线程可根据自己的需要往key中填入不同的值,这就相当于提供了一个同名而不同值的全局变量,一键多值。
  3. 一个线程中可以有多个key
    在这里插入图片描述

2 相关函数

int pthread_key_create(pthread_key_t *key, void (*destructor) (void *))
创建成功返回0,失败返回errno

destructor定义后,当线程结束时,会调用该函数来完成key指向内存清理

int pthread_key_delete(pthread_key_t key);
成功返回0,失败返回errno
man手册解释如下,cleanup操作可以在pthread_key_delete调用前后,pthread_key_delete只负责删除key指针,但是cleanup是destructor函数完成

It is the responsibility of the application to free any application storage or perform any cleanup actions for data structures related to the deleted key or associated thread-specific data in any threads; this cleanup can be done either before or after pthread_key_delete() is called.
int pthread_setspecific(pthread_key_t key, const void *value);
成功返回0,失败返回errno
设置key指向的值
void * pthread_getspecific(pthread_key_t key);
成功返回0,失败返回errno
返回指向的值的指针

3 测试代码

下面写了测试代码

  1. 两个线程中,都使用了一个key,但是指向的是不同的值
  2. fun()中使用pthread_getspecific获取线程内部全局变量,省去传参
#include <iostream>

using namespace std;
pthread_t tid1,tid2;
pthread_key_t key;
void deleter(void* key)
{
    cout<<"deleter"<<key<<endl;

    free(key);  //清理内存

}
void* thread_fun2(void*)
{
    int *myValue = new int(2);
    int priValue = 11;
    pthread_setspecific(key,(void*)myValue);
    printf("thread2:%lu return %d\n", pthread_self(), *(int*)pthread_getspecific(key));
    printf("priValue is %d\n",priValue);

}
void fun()
{
    cout<<"fun"<<*(int*)pthread_getspecific(key)<<endl;//myValue就是线程内部的全局变量
}
void* thread_fun1(void*)
{
    int priValue = 10;
    int *myVec = new int[10];
    cout<<"myVec"<<myVec<<endl;
    myVec[0] = 22;
    myVec[1] = 33;
    pthread_setspecific(key,(void*)myVec);
    pthread_create(&tid2,NULL,thread_fun2,NULL);
    printf("thread1:%lu return %d\n", pthread_self(), *(int*)pthread_getspecific(key));
    fun();
}

int main()
{
    pthread_key_create(&key, deleter);  //创建key和删除器
    cout<<"go"<<endl;
    pthread_create(&tid1,NULL,thread_fun1,NULL);

    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);

    pthread_key_delete(key);  //在删除key之前,要先清理线程
    cout<<"end"<<endl;

    return 0;


}
xili271948@er04180p:/data/lxz/muduo_test/pthread_key$ ./copymain go
myVec0x7fd4e0000b20
thread1:140552344831744 return 22
22
deleter0x7fd4e0000b20
thread2:140552267888384 return 2
priValue is 11
deleter0x7fd4d8000b20
end

4 muduo中的tsd

4.1 muduo的tsd怎么用

value()函数做了如下工作

  1. 先pthread_getspecific,如果key没有设置过值,则new T,再set
  2. 如果key设置了值,则返回get的值
  3. 注意其返回的是引用,所以可以直接对key指向的值进行更改

每次只需要调用value函数即可,完成get,set等操作。

// 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_THREADLOCAL_H
#define MUDUO_BASE_THREADLOCAL_H

#include "muduo/base/Mutex.h"
#include "muduo/base/noncopyable.h"

#include <pthread.h>

namespace muduo
{

template<typename T>
class ThreadLocal : noncopyable
{
 public:
  ThreadLocal()
  {
    MCHECK(pthread_key_create(&pkey_, &ThreadLocal::destructor));
  }

  ~ThreadLocal()
  {
    MCHECK(pthread_key_delete(pkey_));
  }

  T& value()
  {
    T* perThreadValue = static_cast<T*>(pthread_getspecific(pkey_));
    if (!perThreadValue)
    {
      T* newObj = new T();
      MCHECK(pthread_setspecific(pkey_, newObj));
      perThreadValue = newObj;
    }
    return *perThreadValue;
  }

 private:

  static void destructor(void *x)
  {
    T* obj = static_cast<T*>(x);
    typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1];
    T_must_be_complete_type dummy; (void) dummy;
    delete obj;
  }

 private:
  pthread_key_t pkey_;
};

}  // namespace muduo

#endif  // MUDUO_BASE_THREADLOCAL_H

4.2 muduo 测试代码

#include "muduo/base/ThreadLocal.h"
#include "muduo/base/CurrentThread.h"
#include "muduo/base/Thread.h"

#include <stdio.h>

class Test : muduo::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 muduo::string& name() const { return name_; }
  void setName(const muduo::string& n) { name_ = n; }

 private:
  muduo::string name_;
};

muduo::ThreadLocal<Test> testObj1;
muduo::ThreadLocal<Test> testObj2;

void print()
{
  printf("tid=%d, obj1 %p name=%s\n",
         muduo::CurrentThread::tid(),
         &testObj1.value(),
         testObj1.value().name().c_str());
  printf("tid=%d, obj2 %p name=%s\n",
         muduo::CurrentThread::tid(),
         &testObj2.value(),
         testObj2.value().name().c_str());
}

void threadFunc()
{
  print();
  testObj1.value().setName("changed 1");
  testObj2.value().setName("changed 42");
  print();
}

int main()
{
  testObj1.value().setName("main one");
  print();
  muduo::Thread t1(threadFunc);
  t1.start();
  t1.join();
  testObj2.value().setName("main two");
  print();

  pthread_exit(0);
}

lxz@lxz-VirtualBox:~/liuxz/testmuduo/threadlocal/build$ ./thread_local 
tid=2665, constructing 0x55b96a73ee70
tid=2665, obj1 0x55b96a73ee70 name=main one
tid=2665, constructing 0x55b96a73f2b0
tid=2665, obj2 0x55b96a73f2b0 name=
tid=2666, constructing 0x7fd93c000b20
tid=2666, obj1 0x7fd93c000b20 name=
tid=2666, constructing 0x7fd93c000b50
tid=2666, obj2 0x7fd93c000b50 name=
tid=2666, obj1 0x7fd93c000b20 name=changed 1
tid=2666, obj2 0x7fd93c000b50 name=changed 42
tid=2666, destructing 0x7fd93c000b20 changed 1
tid=2666, destructing 0x7fd93c000b50 changed 42
tid=2665, obj1 0x55b96a73ee70 name=main one
tid=2665, obj2 0x55b96a73f2b0 name=main two
tid=2665, destructing 0x55b96a73ee70 main one
tid=2665, destructing 0x55b96a73f2b0 main two
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值