12.6 线程控制_线程私有数据

来源:互联网 发布:51单片机代号 编辑:程序博客网 时间:2024/06/05 15:35

      线程私有数据是存储和查询与某个线程相关的数据的一种机制。

      在分配线程私有数据之前,需要创建与该数据关联的键。这个键将用于获取对线程私有数据的访问权。使用pthread_key_create创建一个键。

  • #include <pthread.h>
  • int pthread_key_create(pthread_kdy_t *keyp, void (*destructor)(void *));

      当线程退出时,如果数据地址已经被置为非null数值,那么析构函数就会被调用,它唯一的参数就是该数据地址。如果传入的destructor参数为null,就表明没有析构函数与键关联。当线程调用pthread_exit或者线程执行返回,正常退出时,析构函数就会被调用,但如果线程调用了exit、_exit、_Exit、abort或出现其他非正常的退出时,就不会调用析构函数。

      对所有的线程,都可以通过调用pthread_key_delete来取消键与线程私有数据值之间的关联关系。

  • #include <pthread.h>
  • int pthread_key_delete(pthread_key_t *key);

      注意调用pthread_key_delete并不会激活与键关联的析构函数。

      有些线程可能看到某个键值,而其他的线程看到的可能是另一个不同的键值,这取决于系统是如何调度线程的,解决这种竞争的办法是使用pthread_once。

  • #include <pthread.h>
  • pthread_once_t initflag = PTHREAD_ONCE_INIT;
  • int pthread_once(pthread_once_t *initflag, void (*initfn)(void));

      initfla必须是一个非本地变量(即全局或静态变量),而且必须初始化为PTHREAD_ONCE_INIT。

      键一旦创建,就可以通过调用pthread_setspecific函数把键和线程私有数据关联起来。可以通过pthread_getspecific函数获得线程私有数据的地址。

  • #include <pthread.h>
  • void *pthread_getspecific(pthread_key_t key);

返回值:线程私有数据值;若没有值与键关联则返回NULL

  • int pthread_setspecific((pthread_key_t key, const void *value);
    原创粉丝点击