zoukankan      html  css  js  c++  java
  • 线程私有数据(TSD)

    线程中特有的线程存储, Thread Specific Data 。线程存储有什么用了?他是什么意思了?大家都知道,在多线程程序中,所有线程共享程序中的变量。现在有一全局变量,所有线程都可以使用它,改变它的值。而如果每个线程希望能单独拥有它,那么就需要使用线程存储了。表面上看起来这是一个全局变量,所有线程都可以使用它,而它的值在每一个线程中又是单独存储的。这就是线程存储的意义。

    下面说一下线程存储的具体用法。

    l          创建一个类型为 pthread_key_t 类型的变量。

    l          调用 pthread_key_create() 来创建该变量。该函数有两个参数,第一个参数就是上面声明的 pthread_key_t 变量,第二个参数是一个清理函数,用来在线程释放该线程存储的时候被调用。该函数指针可以设成 NULL ,这样系统将调用默认的清理函数。

    l          当线程中需要存储特殊值的时候,可以调用 pthread_setspcific() 。该函数有两个参数,第一个为前面声明的 pthread_key_t 变量,第二个为 void* 变量,这样你可以存储任何类型的值。

    l          如果需要取出所存储的值,调用 pthread_getspecific() 。该函数的参数为前面提到的 pthread_key_t 变量,该函数返回 void * 类型的值。

    下面是前面提到的函数的原型:

    int pthread_setspecific(pthread_key_t key, const void *value);

    void *pthread_getspecific(pthread_key_t key);

    int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));

    下面是一个如何使用线程存储的例子:

    #include <stdio.h>
    #include <pthread.h>
    pthread_key_t   key;
    void echomsg(int t)
    {
            printf("destructor excuted in thread %d,param=%d\n",pthread_self(),t);
    }
    void * child1(void *arg)
    {
            int tid=pthread_self();
            printf("thread %d enter\n",tid);
            pthread_setspecific(key,(void *)tid);
            sleep(2);
            printf("thread %d returns %d\n",tid,pthread_getspecific(key));
            sleep(5);
    }
    void * child2(void *arg)
    {
            int tid=pthread_self();
            printf("thread %d enter\n",tid);
            pthread_setspecific(key,(void *)tid);
            sleep(1);
            printf("thread %d returns %d\n",tid,pthread_getspecific(key));
            sleep(5);
    }
    int main(void)
    {
            int tid1,tid2;
            printf("hello\n");
            pthread_key_create(&key,echomsg);
            pthread_create(&tid1,NULL,child1,NULL);
            pthread_create(&tid2,NULL,child2,NULL);
            sleep(10);
            pthread_key_delete(key);
            printf("main thread exit\n");
            return 0;
    }


    线程的本质:

    其实在Linux 中,新建的线程并不是在原先的进程中,而是系统通过一个系统调用clone() 。该系统copy 了一个和原先进程完全一样的进程,并在这个进程中执行线程函数。不过这个copy 过程和fork 不一样。copy 后的进程和原先的进程共享了所有的变量,运行环境。这样,原先进程中的变量变动在copy 后的进程中便能体现出来。

  • 相关阅读:
    小白的源码阅读之旅_RazorEngine_起因
    Sqlserver_小工具_Json解析
    Sqlserver_小工具_批量字段约束处理
    SqlServer_小工具_获取数据库空间信息获取
    SqlServer_小工具_系统表的使用
    Sqlserver_小工具_字符统计(区分大小写)
    SqlServer_小工具_存储空间单位自适应
    不断优化,重构我的代码-----拖拽jquery插件
    canvas绘制二次贝塞尔曲线----演示二次贝塞尔四个参数的作用
    requestAnimationFrame与setInterval,setTimeout
  • 原文地址:https://www.cnblogs.com/yuxingfirst/p/2608612.html
Copyright © 2011-2022 走看看