线程控制--私有数据
来源:互联网 发布:江苏学信学院传销 知乎 编辑:程序博客网 时间:2024/06/05 10:12
线程私有数据采用了一种被称为一键多值的技术,即一个键对应多个数值。访问数据时都是通过键值来访问,好像是对一个变量进行访问,其实是在访问不同的数据。使用线程私有数据时,首先要为每个线程数据创建一个相关联的键。在各个线程内部,都使用这个公用的键来指代线程数据,但是在不同的线程中,这个键代表的数据是不同的。
操作线程私有数据的函数主要有4个:
int pthread_key_create(pthread_key_t *key,void (*destr_function)(void *));
int pthread_setspecific(pthread_key_t key,const void *pointer));
void *pthread_getspecific(pthread_key_t key);
int pthread_key_delete(pthread_key_t key); pthread_key_create:从Linux的TSD池中分配一项,将其值赋给key供以后访问使用,它的第一个参数key为指向键值的指针,第二个参数为一个函数指针,如果指针不为空,则在线程退出时将以key所关联的数据为参数调用destr_function(),释放分配的缓冲区。key一旦被创建,所有线程都可以访问它,但各线程可以根据自己的需要往key中填入不同的值,这就相当于提供了一个同名而不同值的全局变量,一键多值。一键多值靠的是一个关键数据结构数组,即TSD池其结构如下:
static struct pthread_key_struct pthread_keys[PTHREAD_KEYS_MAX] ={{0,NULL}};创建一个TSD就相当于将结构数组中的某一项设置为“in_use”,并将其索引返回给*key,然后设置destructor函数destr_function。
pthread_setspecific:该函数将pointer的值(不是内容)与key相关联。用pthread_setspecific为一个键指定新的线程数据时,线程必须先释放原有的线程数据用以回收空间。
pthread_getspecific:通过该函数得到与key相关联的数据。pthread_key_delete:该函数用来删除一个键,键所占用的内存将被释放。需要注意的是,键占用的内存被释放,与该键关联的线程数据所占用的内存并不被释放。因此,线程数据的释放必须在释放键之前完成。
例8-4将实现如何创建和使用线程的私有数据,具体代码如下所示。#include <stdio.h>#include <string.h>#include <pthread.h>pthread_key_t key;void * thread2(void *arg){ int tsd = 5; printf("thread %d is running\n",pthread_self()); pthread_setspecific(key,(void *)tsd); printf("thread %d returns %d\n",pthread_self(),pthread_getspecific(key));}void * thread1(void *arg){ int tsd = 0; pthread_t thid2; printf("thread %d is running\n",pthread_self()); pthread_setspecific(key,(void *)tsd); pthread_create(&thid2,NULL,thread2,NULL); sleep(2); printf("thread %d return %d\n",pthread_self(),pthread_getspecific(key));}int main(void){ pthread_t thid1; printf("main thread begins running\n"); pthread_key_create(&key,NULL); pthread_create(&thid1,NULL,thread1,NULL); sleep(5); pthread_key_delete(key); printf("main thread exit\n"); return 0;}编译并执行,结果如下:
$ gcc -o 8-4 8-4.c -g -l pthread
$ ./8-4
main thread begins running
thread -1209746544 is running
thread -1218139248 is running
thread -1218139248 returns 5
thread -1209746544 return 0
main thread exit
程序说明:程序中,主线程创建了线程thread1,线程thread1创建了线程thread2。两个线程分别将tsd作为线程私有数据。从程序运行结果可以看出,两个线程tsd的修改互不干扰,可以看出thread2先于thread1结束,线程在创建thread2后,睡眠3s等待thread2执行完毕。主线程睡眠5s等待thread1结束。可以看出thread2对tsd的修改并没影响到thread1的tsd的取值。
- 线程控制--私有数据
- 线程控制--私有数据
- 线程控制-私有数据 转自monalisa's_blog
- 12.6 线程控制_线程私有数据
- 线程的私有数据
- 线程与私有数据
- Posix线程私有数据
- 线程私有数据
- 线程私有数据
- 线程私有数据
- linux线程私有数据
- Posix线程私有数据
- 线程私有数据TSD
- 线程私有数据
- 线程私有数据
- 线程私有数据
- Posix线程私有数据
- 线程私有数据TSD
- 深入理解sizeof
- test
- SOA架构是什么
- 一篇精彩的值得大家回味的文章-别了,我的大学
- jquery显示隐藏元素
- 线程控制--私有数据
- IE的fireEvent方法和Firefox下实现fireEvent
- 为什么我们程序员难晋升
- ACMSTEP 3.1.1 超级楼梯 //递推 斐波那契数列
- 细数google和百度
- 联通vac增量对账回执
- wpf学习
- 黑客组织Anonymous扬言11月攻击Facebook
- html中组件的两种隐藏方式(visibility和display)