Glibc 線(xiàn)程資源---__thread & pthread_key_t


前言

前面寫(xiě)了一篇文章《Glibc 線(xiàn)程資源分配與釋放-----線(xiàn)程?!?/a>,其中主要講解了 glibc 在 x86_64 平臺(tái) Linux 系統(tǒng)上的線(xiàn)程棧區(qū)管理。但是這并不是全部的線(xiàn)程資源,本文中我們將介紹另外兩類(lèi)資源的,以 __thread 定義的變量以及 pthread_key_create 創(chuàng)建的鍵值對(duì)資源。我們?nèi)匀灰?x86_64 Linux 平臺(tái)為例,分析的源碼是 glibc-2.25。

__thread 變量

__thread 標(biāo)識(shí)符修飾的全局或靜態(tài)變量是線(xiàn)程獨(dú)立的,線(xiàn)程對(duì)該變量的操作對(duì)其它線(xiàn)程來(lái)說(shuō)是不可見(jiàn)的。然而線(xiàn)程之間共享內(nèi)存空間的,因此要達(dá)到如些效果就需要針對(duì)該變量為每個(gè)線(xiàn)程分配變量的存儲(chǔ)位置。在 Glibc 中, 所有的 __thread 變量是與 pthread 關(guān)聯(lián)存儲(chǔ)的,通過(guò)相對(duì)于 pthread 變量地址的偏移實(shí)現(xiàn)對(duì)變量的尋址。即是說(shuō),pthread 變量的地址是基址。

《Glibc 線(xiàn)程資源分配與釋放-----線(xiàn)程?!?/a>中提到,pthread 是存儲(chǔ)在線(xiàn)程棧內(nèi)存塊中的,在線(xiàn)程棧布局圖中,我們省略了為 __thread 變量預(yù)留的內(nèi)存空間。下圖說(shuō)明了__thread 變量在線(xiàn)程棧內(nèi)存空間中的存儲(chǔ)。

線(xiàn)程棧布局

下面這段代碼可以驗(yàn)證這個(gè)結(jié)論。

#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 函數(shù)取得的是 pthread 的地址。在解答這個(gè)問(wèn)題之間,我們需要先看一下創(chuàng)建線(xiàn)程的 clone 函數(shù) 以及調(diào)用時(shí)傳入的 flags 參數(shù) 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.

這段描述說(shuō)明, 在 x86_64 位系統(tǒng)上,clone 函數(shù)傳入的 newtls 參數(shù)會(huì)作為 fs 寄存器的基地址,并且該地址值能通過(guò) arch_prctl 函數(shù)獲得。在《Glibc 線(xiàn)程資源分配與釋放-----線(xiàn)程?!?/a>中我們也看到了,newtls 傳入的實(shí)參就是 pthread 變量的地址 (pd)。

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

因此,可以說(shuō)明 arch_prctl 函數(shù)獲得的就是線(xiàn)程 pthread 變量的地址值。執(zhí)行一次上面程序的結(jié)果(每次執(zhí)行結(jié)果可能不同):

&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 確實(shí)存入在線(xiàn)程 pthread 地址的下端,不同線(xiàn)程訪(fǎng)問(wèn)的變量的地址是不相同的,但是變量相對(duì)于 pthread 地址的偏移是相同的,在本例中分別是 -8 與 -4。

鍵值對(duì)資源

另外一種創(chuàng)建線(xiàn)程特定數(shù)據(jù)(Tthread-specific data)的方式是通過(guò) pthread_key_create 創(chuàng)建鍵值映射。每個(gè)線(xiàn)程通過(guò)鍵訪(fǎng)問(wèn)線(xiàn)程特定的數(shù)據(jù)。glibc 中鍵集中分配管理,值分開(kāi)存儲(chǔ)的方式提供 TSD 數(shù)據(jù)。

鍵的分配

pthread_key_create 創(chuàng)建的鍵事實(shí)上是一個(gè)無(wú)符號(hào)的整型數(shù)(sysdeps/x86/bits/pthreadtypes.h):

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

glibc 定義了一個(gè)全局?jǐn)?shù)組用于管理鍵是否已被創(chuàng)建,這個(gè)全局?jǐn)?shù)組定義在 nptl/vars.c 中(如下)。每個(gè)鍵都會(huì)對(duì)應(yīng)于數(shù)組中一個(gè) pthread_struct_t 結(jié)構(gòu)體,該結(jié)構(gòu)體描述了鍵是否已正被使用。由數(shù)組定義可以看出, 一個(gè)進(jìn)程中最多個(gè)通過(guò) pthread_key_create 創(chuàng)建 PTHREAD_KEYS_MAX (1024)個(gè)鍵。

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

如下 (sysdeps/nptl/internaltypes.h), pthread_key_struct 中定義一個(gè)序號(hào)值(seq)及一個(gè)用于釋放數(shù)據(jù)的“析構(gòu)函數(shù)” (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 用于判斷對(duì)應(yīng)的鍵是否被創(chuàng)建,若 seq 是奇數(shù)則正被使用,若為偶數(shù)則未被使用。 例如,若 __pthread_keys[3].seq &1 == 0 為 True 則說(shuō)明該鍵 3 沒(méi)有被創(chuàng)建,否則已被創(chuàng)建。 destr 允許應(yīng)用創(chuàng)建鍵時(shí)定義一個(gè)釋放資源的函數(shù)。

鍵值的映射

鍵值的映射信息是存儲(chǔ)在各線(xiàn)程的 pthread 結(jié)構(gòu)體中的。最直接的方法是在每個(gè) pthread 結(jié)構(gòu)體中也定義一個(gè)類(lèi)似于 __pthread_keys 的數(shù)組, 該數(shù)組中存儲(chǔ) key-value 的映射關(guān)系。不過(guò)為了節(jié)約內(nèi)存空間(大部分情況下應(yīng)用只會(huì)使用很少的 key), pthread 并不是直接創(chuàng)建一個(gè)長(zhǎng)度為 1024 的數(shù)組,而是使用了兩級(jí)數(shù)組的方式來(lái)存儲(chǔ)這種映射關(guān)系。先來(lái)看一下 pthread 結(jié)構(gòu)體中存儲(chǔ)映射關(guān)系的變量:

  /* 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 中定義了一個(gè)結(jié)構(gòu)體 pthread_key_data 存儲(chǔ)指向數(shù)據(jù)的指針(data)。同樣的,其中 seq 標(biāo)識(shí)對(duì)應(yīng)的鍵是否被創(chuàng)建。pthread 中定義了一個(gè) pthread_key_data 的數(shù)組 specific_1stblock 以及指針數(shù)組 specific。 當(dāng)鍵較少時(shí),映射關(guān)系直接存儲(chǔ)到 sepcific_1stblock 中,隨著鍵的增加,再分配空間存儲(chǔ)到 specific 中。為了說(shuō)明這個(gè)過(guò)程,我們來(lái)看一下 pthread_setspecific 函數(shù)(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;
}

從函數(shù)中可以看出,如果 key 小于第 specific_1stblock 數(shù)組大?。≒THREA_KEY_2NDLEVEL_SIZE),則直接將 value 的地址直接存儲(chǔ)于 specific_1stblock[key] 處;如果 key 大于或等 PTHREA_KEY_2NDLEVEL_SIZE, 則會(huì)為指針數(shù)組 sepcific 分配內(nèi)存空間(如果未曾分配),并將 value 的地址位于 specific[idx1st][idx2nd] 處。其中 idx1st、idx2nd 分別是 key 除 PTHREA_KEY_2NDLEVEL_SIZE 的商與余數(shù)。由于大部分應(yīng)用使用的 key 的數(shù)量很小,所以 specific 數(shù)組大部分指針都為 NULL。

可以看出,通過(guò) key 訪(fǎng)問(wèn)線(xiàn)程特定數(shù)據(jù)的步驟比 __thread 變量更為復(fù)雜一些。在 x86_64 架構(gòu)上, fs 寄存器已經(jīng)存儲(chǔ)了線(xiàn)程 pthread 的地址值,因此訪(fǎng)問(wèn) __thread 變量直接通過(guò) fs 相對(duì)尋址即可,只需要一條指令。而 pthread_getspecific 訪(fǎng)問(wèn)線(xiàn)程特定數(shù)據(jù)時(shí),需要通過(guò) specific_1stblock 數(shù)組來(lái)完成,其中還包括了諸多的有效性檢驗(yàn)。效率上 __thread 變量的訪(fǎng)問(wèn)應(yīng)該會(huì)更高一些。但是兩者的差距有多大,需要真實(shí)實(shí)驗(yàn)去測(cè)試一下。

相關(guān)閱讀更多精彩內(nèi)容

  • 轉(zhuǎn)自:Youtherhttps://www.cnblogs.com/youtherhome/archive/201...
    njukay閱讀 1,724評(píng)論 0 52
  • 簡(jiǎn)介 線(xiàn)程創(chuàng)建 線(xiàn)程屬性設(shè)置 線(xiàn)程參數(shù)傳遞 線(xiàn)程優(yōu)先級(jí) 線(xiàn)程的數(shù)據(jù)處理 線(xiàn)程的分離狀態(tài) 互斥鎖 信號(hào)量 一 線(xiàn)程創(chuàng)...
    第八區(qū)閱讀 8,714評(píng)論 1 6
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,715評(píng)論 19 139
  • 人一閑下來(lái)就會(huì)胡思亂想,就像我現(xiàn)在??偸腔孟敕N種方式再次和你相遇,可這么久過(guò)去了,我發(fā)現(xiàn)真的是幻想。你不知道我有多...
    堇小琦閱讀 307評(píng)論 0 1
  • 黎明 前提有很多 結(jié)果就一個(gè) 天就快要亮了 據(jù)說(shuō)一個(gè)懶漢撿了一條死魚(yú) 翻在鍋底 風(fēng) 給你一些氣味 嗅出了花開(kāi)花落 ...
    兔子的蹩腳閱讀 292評(píng)論 0 0

友情鏈接更多精彩內(nèi)容