pthread_key_setspecific和pthread_key_getspecific 用法
2013-03-28 10:17
274 查看
pthread_setspecific(key,(void *)tsd);
相当于key=tsd。让别的函数也可以用到tsd的值。如果我们在线程中用到全局变量,但是只是这个全局变量key,但是每个线程都有他的独立空间,虽然key名字一样,但是存储的空间是不一样,做到每个线程对这个全局变量互不影响。这个全局空间的大小是(void *)类型,也就是4个字节空间。
#include <stdio.h> #include <string.h> #include <pthread.h> #include <unistd.h> pthread_key_t key; void test_xiayu(void) { printf(" test thread %p returns %d\n",pthread_self(),pthread_getspecific(key)); } void * thread2(void *arg) { int tsd = 5; printf("thread2 %p is running\n",pthread_self()); pthread_setspecific(key,(void *)tsd);/* 将tsd值为5设置到key中*/ tsd=7; //printf("thread2 %p returns %d\n",pthread_self(),pthread_getspecific(key)); test_xiayu(); return NULL; } void * thread1(void *arg) { int tsd = 0; pthread_t thid2; printf("thread1 %p is running \n",pthread_self()); pthread_setspecific(key,(void *)tsd);/*将tsd值为 0设置到key中*/ pthread_create(&thid2,NULL,thread2,NULL); sleep(2); test_xiayu(); //printf("thread1 %p returns %d\n",pthread_self(),pthread_getspecific(key)); return NULL; } void test1() { pthread_t thid1; printf("main thread begins running\n"); pthread_key_create(&key,NULL); pthread_create(&thid1,NULL,thread1,NULL); sleep(3); pthread_key_delete(key); printf("main thread exit\n"); } int main(int argc, char **argv) { #if 1 test1(); #endif return 0; } /** * * 主线程创建了线程thread1,线程thread1创建了thread2.两个线程分别将tsd作 * * 为线程私有数据。从程序运行结果可以看出,两个线程tsd的修改互不干扰,可 * * 以看出thread2先于thread1结束,线程在创建thread2后,睡眠5秒等待thread2 * * 执行完毕。可以看出thread2对tsd的修改并没影响到thread1的tsd的取值. * */
相关文章推荐
- pthread_key_setspecific和pthread_key_getspecific 用法
- pthread_create,pthread_once,pthread_key_create,pthread_key_delete,pthread_getspecific,pthread_setspecific()
- pthread_once、pthread_key_create和pthread_getspecific和pthread_setspecific
- pthread_once,pthread_key_create,pthread_setspecific,pthread_getspecific
- pthread_getspecific()和pthread_setspecific()的使用方法
- 线程数据共享:pthread_getspecific和pthread_setspecific
- pthread库中操作线程专有数据的函数:pthread_key_create,pthread_setspecific,pthread_gtespecific,pthread_key_delete
- pthread_getspecific和pthread_setspecific使用
- pthread_getspecific和pthread_setspecific使用
- pthread_getspecific和pthread_setspecific使用
- pthread_getspecific和pthread_setspecific使用
- pthread_setspecific,pthread_getspecific
- pthread_getspecific()--读线程私有数据|pthread_setspecific()--写线程私有数据
- pthread_getspecific()--读线程私有数据|pthread_setspecific()--写线程私有数据
- TSD中的几个函数,pthread_key_create pthread_getspecific
- 线程局部存储-pthread_getspecific和pthread_setspecific使用
- pthread_key_create用法
- pthread_once和pthread_key_create的用法演示
- pthread_getspecific和pthread_setspecific使用
- TSD相关的 4 个函数: pthread_key_create(); pthread_key_delete(); pthread_getspecific(); pthread_sets