__thread 变量

__thread 标识符修饰的全局或静态变量是线程独立的,线程对该变量的操作对其它线程来说是不可见的。然而线程之间共享内存空间的,因此要达到如些效果就需要针对该变量为每个线程分配变量的存储位置。在 Glibc 中, 所有的 __thread 变量是与 pthread 关联存储的,通过相对于 pthread 变量地址的偏移实现对变量的寻址。即是说,pthread 变量的地址是基址。

《Glibc 线程资源分配与释放-----线程栈》中提到,pthread 是存储在线程栈内存块中的,在线程栈布局图中,我们省略了为 __thread 变量预留的内存空间。下图说明了__thread 变量在线程栈内存空间中的存储。

线程栈布局

下面这段代码可以验证这个结论。

#include <pthread.h>
#include <stdio.h>
#include <asm/prctl.h>
#include <sys/prctl.h>
#include <errno.h>

static int __thread var_1 = 0;
static short  __thread var_2 = 0;

void* func(void *f) {
    
    long pthread_addr = 0;
    arch_prctl(ARCH_GET_FS, &pthread_addr);
    printf("&pthread = %p, &var_1 = %p, off_var_1 = %d,  &var_2 = %p, off_var_2 = %d\n",
            pthread_addr, &var_1, (long)&var_1 - pthread_addr, 
            &var_2, (long)&var_2 - pthread_addr );
    return NULL;
}

int main() {
    pthread_t chs[3];
    int i = 0;

    for (i = 0; i < 3; ++i) {
        pthread_create(&chs[i], NULL, func, NULL);
    }
    
    for (i = 0; i < 3; ++i) {
        pthread_join(chs[i], NULL);
    }
    return 0;
}

上面这段代码中,比较难以理解的在于为什么 arch_prctl 函数取得的是 pthread 的地址。在解答这个问题之间,我们需要先看一下创建线程的 clone 函数 以及调用时传入的 flags 参数 CLONE_SETTLS。

int clone(int (*fn)(void *), void *child_stack,
                 int flags, void *arg, ...
                 /* pid_t *ptid, void *newtls, pid_t *ctid */ );

CLONE_SETTLS
(since Linux 2.5.32) The TLS (Thread Local Storage) descriptor is set to newtls. The interpretation of newtls and the resulting effect is architecture dependent. On x86, newtls is interpreted as a **struct user_desc ** (See set_thread_area(2)). On x86_64 it is the new value to be set for the %fs base register (See the ARCH_SET_FS argument to arch_prctl(2)). On architectures with a dedicated TLS register, it is the new value of that register.

这段描述说明, 在 x86_64 位系统上,clone 函数传入的 newtls 参数会作为 fs 寄存器的基地址,并且该地址值能通过 arch_prctl 函数获得。在《Glibc 线程资源分配与释放-----线程栈》中我们也看到了,newtls 传入的实参就是 pthread 变量的地址 (pd)。

if (__glibc_unlikely (ARCH_CLONE (&start_thread, STACK_VARIABLES_ARGS,
                    clone_flags, pd, &pd->tid, tp, &pd->tid)
            == -1))

因此,可以说明 arch_prctl 函数获得的就是线程 pthread 变量的地址值。执行一次上面程序的结果(每次执行结果可能不同):

&pthread = 0x7f8325948700, &var_1 = 0x7f83259486f8, off_var_1 = -8,  &var_2 = 0x7f83259486fc, off_var_2 = -4
&pthread = 0x7f8324f47700, &var_1 = 0x7f8324f476f8, off_var_1 = -8,  &var_2 = 0x7f8324f476fc, off_var_2 = -4
&pthread = 0x7f8324546700, &var_1 = 0x7f83245466f8, off_var_1 = -8,  &var_2 = 0x7f83245466fc, off_var_2 = -4

可以看出, var_1 与 var_2 确实存入在线程 pthread 地址的下端,不同线程访问的变量的地址是不相同的,但是变量相对于 pthread 地址的偏移是相同的,在本例中分别是 -8 与 -4。

键值对资源

另外一种创建线程特定数据(Tthread-specific data)的方式是通过 pthread_key_create 创建键值映射。每个线程通过键访问线程特定的数据。glibc 中键集中分配管理,值分开存储的方式提供 TSD 数据。

键的分配

pthread_key_create 创建的键事实上是一个无符号的整型数(sysdeps/x86/bits/pthreadtypes.h):

/* Keys for thread-specific data */
typedef unsigned int pthread_key_t;

glibc 定义了一个全局数组用于管理键是否已被创建,这个全局数组定义在 nptl/vars.c 中(如下)。每个键都会对应于数组中一个 pthread_struct_t 结构体,该结构体描述了键是否已正被使用。由数组定义可以看出, 一个进程中最多个通过 pthread_key_create 创建 PTHREAD_KEYS_MAX (1024)个键。

/* Table of the key information.  */
struct pthread_key_struct __pthread_keys[PTHREAD_KEYS_MAX]

如下 (sysdeps/nptl/internaltypes.h), pthread_key_struct 中定义一个序号值(seq)及一个用于释放数据的“析构函数” (destr)。

/* Thread-local data handling.  */
struct pthread_key_struct
{
  /* Sequence numbers.  Even numbers indicated vacant entries.  Note
     that zero is even.  We use uintptr_t to not require padding on
     32- and 64-bit machines.  On 64-bit machines it helps to avoid
     wrapping, too.  */
  uintptr_t seq;

  /* Destructor for the data.  */
  void (*destr) (void *);
};

seq 用于判断对应的键是否被创建,若 seq 是奇数则正被使用,若为偶数则未被使用。 例如,若 __pthread_keys[3].seq &1 == 0 为 True 则说明该键 3 没有被创建,否则已被创建。 destr 允许应用创建键时定义一个释放资源的函数。

键值的映射

键值的映射信息是存储在各线程的 pthread 结构体中的。最直接的方法是在每个 pthread 结构体中也定义一个类似于 __pthread_keys 的数组, 该数组中存储 key-value 的映射关系。不过为了节约内存空间(大部分情况下应用只会使用很少的 key), pthread 并不是直接创建一个长度为 1024 的数组,而是使用了两级数组的方式来存储这种映射关系。先来看一下 pthread 结构体中存储映射关系的变量:

  /* We allocate one block of references here.  This should be enough
     to avoid allocating any memory dynamically for most applications.  */
  struct pthread_key_data
  {
    /* Sequence number.  We use uintptr_t to not require padding on
       32- and 64-bit machines.  On 64-bit machines it helps to avoid
       wrapping, too.  */
    uintptr_t seq;

    /* Data pointer.  */
    void *data;
  } specific_1stblock[PTHREAD_KEY_2NDLEVEL_SIZE];

  /* Two-level array for the thread-specific data.  */
  struct pthread_key_data *specific[PTHREAD_KEY_1STLEVEL_SIZE];

在 pthread 中定义了一个结构体 pthread_key_data 存储指向数据的指针(data)。同样的,其中 seq 标识对应的键是否被创建。pthread 中定义了一个 pthread_key_data 的数组 specific_1stblock 以及指针数组 specific。 当键较少时,映射关系直接存储到 sepcific_1stblock 中,随着键的增加,再分配空间存储到 specific 中。为了说明这个过程,我们来看一下 pthread_setspecific 函数(nptl/pthread_setspecific.c):

int
__pthread_setspecific (pthread_key_t key, const void *value)
{
  struct pthread *self;
  unsigned int idx1st;
  unsigned int idx2nd;
  struct pthread_key_data *level2;
  unsigned int seq;

  self = THREAD_SELF;

  /* Special case access to the first 2nd-level block.  This is the
     usual case.  */
  if (__glibc_likely (key < PTHREAD_KEY_2NDLEVEL_SIZE))
    {
      /* Verify the key is sane.  */
      if (KEY_UNUSED ((seq = __pthread_keys[key].seq)))
    /* Not valid.  */
    return EINVAL;

      level2 = &self->specific_1stblock[key];

      /* Remember that we stored at least one set of data.  */
      if (value != NULL)
    THREAD_SETMEM (self, specific_used, true);
    }
  else
    {
      if (key >= PTHREAD_KEYS_MAX
      || KEY_UNUSED ((seq = __pthread_keys[key].seq)))
    /* Not valid.  */
    return EINVAL;

      idx1st = key / PTHREAD_KEY_2NDLEVEL_SIZE;
      idx2nd = key % PTHREAD_KEY_2NDLEVEL_SIZE;

      /* This is the second level array.  Allocate it if necessary.  */
      level2 = THREAD_GETMEM_NC (self, specific, idx1st);
      if (level2 == NULL)
    {
      if (value == NULL)
        /* We don't have to do anything.  The value would in any case
           be NULL.  We can save the memory allocation.  */
        return 0;

      level2
        = (struct pthread_key_data *) calloc (PTHREAD_KEY_2NDLEVEL_SIZE,
                          sizeof (*level2));
      if (level2 == NULL)
        return ENOMEM;

      THREAD_SETMEM_NC (self, specific, idx1st, level2);
    }

      /* Pointer to the right array element.  */
      level2 = &level2[idx2nd];

      /* Remember that we stored at least one set of data.  */
      THREAD_SETMEM (self, specific_used, true);
    }

  /* Store the data and the sequence number so that we can recognize
     stale data.  */
  level2->seq = seq;
  level2->data = (void *) value;

  return 0;
}

从函数中可以看出,如果 key 小于第 specific_1stblock 数组大小(PTHREA_KEY_2NDLEVEL_SIZE),则直接将 value 的地址直接存储于 specific_1stblock[key] 处;如果 key 大于或等 PTHREA_KEY_2NDLEVEL_SIZE, 则会为指针数组 sepcific 分配内存空间(如果未曾分配),并将 value 的地址位于 specific[idx1st][idx2nd] 处。其中 idx1st、idx2nd 分别是 key 除 PTHREA_KEY_2NDLEVEL_SIZE 的商与余数。由于大部分应用使用的 key 的数量很小,所以 specific 数组大部分指针都为 NULL。

可以看出,通过 key 访问线程特定数据的步骤比 __thread 变量更为复杂一些。在 x86_64 架构上, fs 寄存器已经存储了线程 pthread 的地址值,因此访问 __thread 变量直接通过 fs 相对寻址即可,只需要一条指令。而 pthread_getspecific 访问线程特定数据时,需要通过 specific_1stblock 数组来完成,其中还包括了诸多的有效性检验。效率上 __thread 变量的访问应该会更高一些。但是两者的差距有多大,需要真实实验去测试一下。