zoukankan      html  css  js  c++  java
  • Thread-Local Storage for C99

       线程本地存储(TLS)是一种机制,通过这样的机制进行变量分配。在每一个现存线程都有一个实例变量。这样的执行模型GCC用来实现这个,起源于IA-64处理器,可是已经被迁移到其它的处理器。它须要大量的支持连接器(ld)、动态连接器(ld.so)和系统库(libc.so和libpthread.so),所以不是到处都可用的。

       在用户层,一个新的存储类扩展keyword:__thread.比如:

    __thread int i;
    extern __thread struct state s;
    static __thread char *p;
          这个keyword__thread能够单独使用。也能够和extern或者static配合使用,不能与其它的存储类说明符使用。当使用extern或者static。__thread必须在这些存储keyword后面使用。

        看以下的样例:

       
    /*File : thread.c
     *Auth : sjin
     *Date : 20141023
     *Mail : 413977243@qq.com
     */
    
    #include <stdio.h>
    #include <pthread.h>
    
    #define MAX_THREADS 2
    
    static __thread int i = 1;
    
    void *thr_func(void *arg)
    {
        printf("pself = %d,i = %d
    ",pthread_self(),i);
            i = ( int)pthread_self();
        printf("pself = %d,i = %d
    ",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=18316
    2、https://gcc.gnu.org/onlinedocs/gcc-3.3.1/gcc/Thread-Local.html
  • 相关阅读:
    Servlet介绍(一)
    iOS Dev (50)用代码实现图片加圆角
    Codeforces Round #265 (Div. 2) D. Restore Cube 立方体推断
    JVM:垃圾回收机制和调优手段
    Memcachedclient-XMemcached使用
    JVM中类的卸载机制
    血型统计
    iOS 事件传递及响应过程
    java 对象参数去空格方式
    spring aop 一个挡板例子
  • 原文地址:https://www.cnblogs.com/gccbuaa/p/6718491.html
Copyright © 2011-2022 走看看