【问题标题】:gcc: Thread-local variable compiled as BSSgcc:编译为 BSS 的线程局部变量
【发布时间】:2015-12-01 15:38:04
【问题描述】:

我是新用户并在我的 i686/32 位架构的 Ubuntu 14.04 计算机上使用 gcc(版本 4.8.2)测试 thread-local storage (TLS) 类。

为了确定__thread 关键字是否具有预期的效果,我用gcc test.c 编译了这个简约的测试程序(没有错误或警告):

#include <stdio.h>

__thread int i;

int main() {
  i = 7;
  printf("%d\n",i);
}

并使用工具nm检查目标代码中符号i的存储类:

nm a.out | grep ' i'

结果是

00000000 B i

这意味着i 被视为一个通用的全局未初始化变量(存储在 BSS 部分中)。根据man nm,线程本地存储变量用字母L表示,而不是B

这里有什么问题?

这是nm 问题还是真正的问题?

【问题讨论】:

    标签: c multithreading gcc nm


    【解决方案1】:

    没问题,就是nm(1)写输出的方式。

    nm(1) 的默认输出格式(和信息)因平台而异(例如,我的 Linux 桌面中 nm(1) 的手册页甚至没有提到线程本地存储的 L)。

    但是,如果您使用-fs 启用 SysV 输出格式,您将获得更详细的输出:

    $ nm -fs a.out
    Symbols from a.out:
    
    Name                  Value           Class        Type         Size             Line  Section
    
    ...
    
    i                   |0000000000000000|   B  |               TLS|0000000000000004|     |.tbss
    ...
    

    如您所见,使用这种输出格式i 被标识为Type 列下的线程本地,它位于.tbss 中。

    如果您的发行版手册页提到了用于线程本地存储的L 标志,而您在默认输出格式中看不到它,我会说这是nm(1) 中的一个错误。

    【讨论】:

    • 就是这样。感谢您的解释,确实我得到了相同的输出。至于手册页,我在网络上的一个 UNIX 手册页上没有意识到。
    【解决方案2】:

    您的代码太少了。线程数要到运行时才能知道,因此您在可执行文件中看到的变量是main 将使用的变量。当创建额外的线程时,将分配变量的额外副本。

    这是一个演示线程变量的最小程序。

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    
    __thread int i;
    
    void *foo( void *args )
    {
        i = 8;
        printf( "foo: %d\n", i );
        return NULL;
    }
    
    int main( void )
    {
        i = 7;
        printf( "main:%d\n", i );
    
        pthread_t pid;
        if ( pthread_create( &pid, NULL, foo, NULL ) != 0 )
            exit( 1 );
    
        pthread_join( pid, NULL );
        printf( "main:%d\n", i );
    }
    

    【讨论】:

    • 感谢您提供这个代码框架,它实际上对我打算编写的真实程序很有帮助!但是对于这个问题,我的问题更多是关于理解nm 输出,所以Filipe Gonçalves 明白了这一点(他向我展示了如何使用nm -fs 检查存储类)。
    猜你喜欢
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多