gcc`__thread`如何工作?

xiv*_*r77 21 c multithreading gcc thread-local-storage

如何__thread实现gcc?它只是一个包装pthread_getspecificpthread_setspecific

我的程序使用posix API进行TLS,现在我看到30%的程序运行时都用在了上面,我感到很失望pthread_getspecific.我在每个需要资源的函数调用的条目上调用它.pthread_getspecific在内联优化之后,编译器似乎没有优化.因此,在内联函数之后,代码基本上一次又一次地搜索正确的TLS指针以获得返回的相同指针.

__thread在这种情况下会帮助我吗?我知道thread_localC11中有,但我所拥有的gcc还不支持它.(但现在我看到我的gcc确实支持_Thread_local不是宏.)

我知道我可以简单地测试一下然后看看.但是我现在必须去别的地方了,在我尝试重大改写之前,我想更好地了解一个功能.

Bas*_*tch 13

最近的GCC,例如GCC 5确实支持C11及其thread_local(如果用例如编译gcc -std=c11).正如FUZxxl所评论的那样,您可以使用(而不是C11 thread_local)__thread旧版GCC支持的限定符.阅读线程本地存储.

pthread_getspecific确实很慢(它在POSIX库中,因此不是由GCC提供,而是由GNU glibcmusl-libc提供),因为它涉及函数调用.使用thread_local变量很可能会更快.

查看MUSL thread/pthread_getspecific.c文件的源代码以获取 实现示例.阅读相关问题的答案.

_threadthread_local被(通常)奇迹般地转化为呼叫pthread_getspecific.它们通常涉及一些特定的地址模式和/或寄存器(细节是特定于实现的,与ABI相关;在Linux上,我想由于x86-64有更多的寄存器和地址模式,它的TLS实现比在i386上更快),在编译器,链接器运行时系统的帮助下.相反,有些实现pthread_getspecific正在使用一些内部thread_local变量(在你的POSIX线程的实现中).

例如,编译以下代码

#include <pthread.h>

const extern pthread_key_t key;

__thread int data;

int
get_data (void) {
  return data;
}

int
get_by_key (void) {
  return *(int*) (pthread_getspecific (key));
}
Run Code Online (Sandbox Code Playgroud)

使用GCC 5.2(在Debian/Sid上),gcc -m32 -S -O2 -fverbose-asm给出了get_data使用TLS 的以下代码:

  .type get_data, @function
get_data:
.LFB3:
  .cfi_startproc
  movl  %gs:data@ntpoff, %eax   # data,
  ret
.cfi_endproc
Run Code Online (Sandbox Code Playgroud)

和下面的代码get_by_key显式调用pthread_getspecific:

get_by_key:
 .LFB4:
  .cfi_startproc
  subl  $24, %esp   #,
  .cfi_def_cfa_offset 28
  pushl key # key
  .cfi_def_cfa_offset 32
  call  pthread_getspecific #
  movl  (%eax), %eax    # MEM[(int *)_4], MEM[(int *)_4]
  addl  $28, %esp   #,
  .cfi_def_cfa_offset 4
  ret
  .cfi_endproc
Run Code Online (Sandbox Code Playgroud)

因此,使用TLS __thread(或thread_local在C11中)应该比使用更快pthread_getspecific(避免调用的开销).

请注意,这thread_local是(C11标准头文件)中定义<threads.h>便捷宏.