线程的私有数据(TSD-Thread-Specific Data)

来源:互联网 发布:三角衣柜淘宝店铺质量 编辑:程序博客网 时间:2024/05/18 02:47

      在线程内部,线程私有数据可以被各个函数访问到,但它对其他线程是屏蔽的。

      使用线程数据时,首先要为每个线程数据创建一个相关联的键。在各个线程内部,都使用这个公用的键来指代线程数据,但是在不同的线程中,这个键代表的数据是不同的。也就是说,key一旦被创建,所有线程都可以访问它,但各线程可根据自己的需要往key中填入不同的值。这相当于提供了一个同名而不同值的全局变量,一键多值。

      操作线程私有数据的函数主要有4个:

  • pthread_key_create(创建一个键)
  • pthread_setspecific(为一个键设置线程私有数据)
  • pthread_getspecific(从一个键读取线程私有数据)
  • pthread_key_delete(删除一个键)

      以下代码示例如何创建、使用和删除线程的私有数据:

#include <stdio.h>#include <string.h>#include <pthread.h>//声明键pthread_key_t key;//线程1中设置本线程的私有数据为5,并且之后获取这个数据并打印到屏幕void * thread1(void *arg){    int tsd=5;    printf("Thread %u is running\n",pthread_self());    pthread_setspecific(key,(void*)tsd);    printf("Thread %u returns %d\n",pthread_self(),pthread_getspecific(key));}//线程2中设置本线程的私有数据为4,并且之后获取这个数据并打印到屏幕void * thread2(void *arg){    int tsd=4;    printf("Thread %u is running\n",pthread_self());    pthread_setspecific(key,(void*)tsd);    printf("Thread %u returns %d\n",pthread_self(),pthread_getspecific(key));}int main(void){    pthread_t thid1,thid2;    printf("Main thread begins running\n");//创建这个键    pthread_key_create(&key,NULL);//创建2个子线程    pthread_create(&thid1,NULL,thread1,NULL);    pthread_create(&thid2,NULL,thread2,NULL);//等待2个子线程返回    int status1,status2;    pthread_join(thid1,(void *)&status1);    pthread_join(thid2,(void *)&status2);//删除键    pthread_key_delete(key);    printf("main thread exit\n");    return 0;}

运行结果:



      上述2个线程分别将tsd作为线程私有数据。从程序运行来看,两个线程对tsd的修改互不干扰。

阅读全文
0 0
原创粉丝点击