至于使用这个东西的意义,想不通,既然想特定线程,为什么不保存在线程栈里呢?
/**
* @file specific.c
* 特定于线程的数据
*/
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
pthread_key_t key;
pthread_once_t once = PTHREAD_ONCE_INIT;
// 自定义的析构函数,用于销毁
void destructor(void *ptr)
{
free(ptr);
}
// once函数
void my_once(void)
{
// 键和对应的析构函数
pthread_key_create(&key, destructor);
}
// 业务函数
void fun(void)
{
// ...
pthread_once(&once, my_once);
char *ptr;
// 从key数组里找出第一个空闲的
if ((ptr = pthread_getspecific(key)) == NULL)
{
ptr = malloc(...);
// 保存回去
pthread_setspecific(key, ptr);
}
// 使用ptr,ptr就是只属于这个线程的数据
}