gpt4 book ai didi

c - gcc `__thread` 是如何工作的?

转载 作者:太空狗 更新时间:2023-10-29 16:27:08 26 4
gpt4 key购买 nike

gcc中的__thread是如何实现的?它只是 pthread_getspecificpthread_setspecific 的包装器吗?

我的程序使用 TLS 的 posix API,现在我有点失望,因为我的程序运行时间有 30% 花在了 pthread_getspecific 上。我在每个需要资源的函数调用的入口调用它。在内联优化之后,编译器似乎没有优化掉 pthread_getspecific。所以在函数被内联后,代码基本上是一次又一次地搜索正确的 TLS 指针以获得相同的指针返回。

__thread 会在这种情况下帮助我吗?我知道C11有thread_local,但是我的gcc还不支持。 (但现在我看到我的 gcc 确实支持 _Thread_local 只是不支持宏。)

我知道我可以简单地测试一下看看。但我现在必须去别的地方,我想在尝试进行相当大的重写之前更好地了解某个功能。

最佳答案

最近 GCC ,例如GCC 5支持 C11 及其 thread_local (如果使用例如 gcc -std=c11 进行编译)。作为FUZxxl评论,你可以使用(而不是 C11 thread_local ) __thread旧版 GCC 支持的限定符。了解 Thread Local Storage .

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

查看MUSL's thread/pthread_getspecific.c file的源代码一个实现的例子。阅读this answer一个相关的问题。

_thread & thread_local (通常)不会神奇地转换为对 pthread_getspecific 的调用.它们通常涉及一些特定的地址模式和/或寄存器(细节是特定于实现的,与 ABI 相关;在 Linux 上,我猜想因为 x86-64 有更多的寄存器和地址模式,它的 TLS 实现比在 i386 上更快), 在 compiler 的帮助下, linkerruntime system .相反,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));
}

使用 GCC 5.2(在 Debian/Sid 上)和 gcc -m32 -S -O2 -fverbose-asmget_data 给出以下代码使用 TLS:

  .type get_data, @function
get_data:
.LFB3:
.cfi_startproc
movl %gs:data@ntpoff, %eax # data,
ret
.cfi_endproc

和以下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

因此将 TLS 与 __thread 结合使用(或 C11 中的 thread_local)可能比使用 pthread_getspecific 更快(避免调用的开销)。

注意 thread_localconvenience macro defined in <threads.h> (C11 标准 header )。

关于c - gcc `__thread` 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32245103/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com