IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [译]Thread-Local Storage for C99

    jsh13417发表于 2014-10-23 09:31:15
    love 0
    线程本地存储(TLS)是一种机制,通过这种机制进行变量分配,在每个现存线程都有一个实例变量。这种运行模型GCC用来实现这个,起源于IA-64处理器,但是已经被迁移到其他的处理器。它需要大量的支持连接器(ld)、动态连接器(ld.so)和系统库(libc.so和libpthread.so),所以不是到处都可用的。 在用户层,一个新的存储类扩展关键字:__thread.例如:__thread int i; extern __thread struct state s; static __thread char *p; 这个关键字__thread可以单独使用,也可以和extern或者static配合使用,不能与其他的存储类说明符使用。当使用extern或者static,__thread必须在这些存储关键字后面使用。 看下面的例子: /*File : thread.c *Auth : sjin *Date : 20141023 *Mail : 413977243@qq.com */ #include #include #define MAX_THREADS 2 static __thread int i = 1; void *thr_func(void *arg) { printf("pself = %d,i = %d\n",pthread_self(),i); i = ( int)pthread_self(); printf("pself = %d,i = %d\n",pthread_self(),i); } int main() { int j = 0; pthread_t thread_id[MAX_THREADS]; for(j = 0; j < MAX_THREADS;j++){ pthread_create(&thread;_id[j],0,thr_func,NULL); } for(j = 0; j < MAX_THREADS;j++){ pthread_join(thread_id[j],NULL); } return 0; }运行结果:pself = -1218581696,i = 1 pself = -1218581696,i = -1218581696 pself = -1226974400,i = 1 pself = -1226974400,i = -1226974400参考资料: 1、https://bugs.gentoo.org/show_bug.cgi?id=183162、https://gcc.gnu.org/onlinedocs/gcc-3.3.1/gcc/Thread-Local.html


沪ICP备19023445号-2号
友情链接