在多线程环境下,每个线程都需要处理自身的私有数据,如:数据库连接、Socket连接等。
Linux下C语言使用了一种被称为一键多值的技术来使线程数据私有化。使用线程私有数据时,首先要为每个线程数据创建一个相关联的键。在各个线程内部,都使用这个公共的键来指代线程数据,但是在不同的线程中,这个键代表的数据是不同的。
示例程序:
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
// 声明一个key,用于关联线程的私有数据
pthread_key_t key;
void *thread2(void *arg)
{
int tsd = 5;
printf("thread %ld is running\n", (unsigned long int)pthread_self());
pthread_setspecific(key, (void *)&tsd);
int result = *((int *)pthread_getspecific(key));
printf("thread %ld returns %d\n", pthread_self(), result);
}
void *thread1(void *arg)
{
int tsd = 1;
pthread_t thid2;
printf("thread %ld is running\n", (unsigned long int)pthread_self());
// 为key赋值,此值只能由本线程使用
// 为key指定新数据时,必须释放原有数据占据的内存空间
pthread_setspecific(key, (void *)