linux线程的私有数据保护

(转载)http://www.cppblog.com/prayer/archive/2009/07/05/89286.html

linux下的线程真是很有趣,各种在windows编程里看不到的技巧在这里尽显无余。在一个进程里有许多的线程,这些线程共享进程里的所有资源。包括数据空间,所以全局变量是为所有的线程所共享的。但如果线程里的全局变量为所有的线程所共享会出现一些问题。比如如果代码量很大的话那么名字的命名都是一个问题。如果两个线程有相同的全局erron变量那么线程2可以会用到线程1的出错提示。

这个问题可以通过创建线程的私有数据来解决(thread-specific Data,TSD)。一个线程里的TSD只有这个线程可以访问。

TSD采用了一种称之为私有数据的技术,即一个键对应多个数据值。意思就好比用一个数据结构,这个结构的结构名就是键值,在这个结构里有许多的数据,这些数据封闭在这个结构里。线程可以通过这个结构名即键值来访问其所属的数据结构。

创建TSD有三个步骤:创建一个键(即创建一个数据结构),为这个键设置线程的私有数据(即为这个结构体里的数据赋值)。删除键值。

三个步骤分别对应的系统函数了:

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

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

int pthread_key_delete(pthread_key_t key);

 

创建了TSD后线程可以用下面的函数来读取数据。

void *pthread_getspecific(pthread_key_t key);

 

下面代码演示创建TSD

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<pthread.h>
 4 
 5 pthread_key_t key;
 6 
 7 void *thread2(void *arg)
 8 {
 9     int tsd=5;
10     printf("thread %u is running\n",pthread_self());
11 
12     pthread_setspecific(key,(void*)tsd);
13     printf("thread %u returns %d\n",pthread_self(),pthread_getspecific(key));
14 }
15 
16 void *thread1(void *arg)
17 {
18     int tsd=0;
19     pthread_t thid2;
20 
21     printf("thread %u is running \n",pthread_self());
22 
23     pthread_setspecific(key,(void*)tsd);
24     pthread_create(&thid2,NULL,thread2,NULL);
25     sleep(5);
26     printf("thread %u returns %\n",pthread_self(),pthread_getspecific(key));
27 }
28 
29 int main()
30 {
31     pthread_t thid1;
32     printf("main thread begins running \n");
33 
34     pthread_key_create(&key,NULL);
35     pthread_create(&thid1,NULL,thread1,NULL);
36 
37     sleep(3);
38     pthread_key_delete(key);
39     printf("main thread exit\n");
40 
41     return 0;
42 }

 

程序首先包涵所须的头文件。程序分三个函数,thread2()thread1(),main()。线程2通过线程一的函数来创建。在main()函数里通过调用pthread_key_create()创建了一个TSD键值key。然后调用pthread_create()函数创建线程1。线程1开始运行。在线程函数里有要保护的私有数据tsd=0;

通过调用pthread_key_setspecific()函数把tsd设置到键值key当中。接着调用pthread_create()创建线程2。然后沉睡5秒,最后通过调用pthread_key_getspecific(),打印出键值。在线程2函数里先定义要保护的私有数据tsd=5;然后调用pthread_key_specific()函数设置tsd5key里。

在编译的时候要用到pthread.a库,形式为:

ong@ubuntu:~/myjc/myc$ gcc -o tsd tsd.c -lpthread

原文地址:https://www.cnblogs.com/Robotke1/p/3048039.html