天天看点

linux api笔记(6):线程(四) 线程私有数据

本文将描述线程的一个比较重要的一方面:线程私有数据,如下代码:

#include <pthread.h>

#include <unistd.h>

#include <stdio.h>

pthread_key_t kKey = 0;

void * ThreadProc(void* arg)

{

char* a = (char*)(arg);

sleep(2);

pthread_setspecific(kKey, a);

sleep(1);

char* str = (char*)pthread_getspecific(kKey);

printf("thread: %s/n", str);

}

int main()

{

pthread_t thread_handle1 = 0;

pthread_t thread_handle2 = 0;

char a[] = {"i am A"};

char b[] = {"i am B"};

pthread_create(&thread_handle1, NULL, ThreadProc, a);

pthread_key_create(&kKey, NULL);

pthread_create(&thread_handle2, NULL, ThreadProc, b);

void* out1 = NULL;

void* out2 = NULL;

pthread_join(thread_handle1, &out1);

pthread_join(thread_handle2, &out2);

return 0;

}

使用线程私有数据的步骤:

1)使用pthread_key_create分配一个线程私有数据的key,这里需要注意的是当我们调用了这个函数

之后进程中所有的线程都可以使用这个key,并且通过这个key获取到的私有数据是互不相同的,比如线程

A通过key设置了数据D,但线程B并没有设置数据,那么A通过key获取的数据当然是D,而B获取的是一个

空的值。另外需要注意的是不管线程是在pthread_key_create调用之前或之后产生,它都能够在函数调用

之后使用这个key。

2)使用pthread_setspecific函数将key和一个线程私有数据绑定。

3)通过pthread_getspecific函数和key获取到这个线程的私有数据。

我一直觉得线程私有数据策略很好用,但考虑到使用过程中需要进行“系统调用”(pthread_getspecific是系统调用吗?),

如果比较频繁地调用这个函数的话说不定会使程序的性能下降,但看了man文档中的一句话后这个中顾虑稍微减轻,尽管还是有疑问:

“the function to pthread_getspecific()  has  been  designed  to  favor speed and simplicity over error reporting”

上面说它的速度已经被设计地很快了。

继续阅读