pthread_getspecific 或 pthread_setspecific 子例程

用途

返回并设置与指定键关联的特定于线程的数据。

线程库 (libpthreads.a)

语法

#include <pthread.h>
void *pthread_getspecific (key)
pthread_key_t key;
int pthread_setspecific (key, value)
pthread_key_t key; 
const void *value;

描述

pthread_setspecific 函数将特定于线程的 与通过先前调用 pthread_key_create获取的 相关联。 不同的线程可能会将不同的值绑定到同一个键。 这些值通常是指向已保留供调用线程使用的动态分配内存块的指针。

pthread_getspecific 函数返回当前代表调用线程绑定到指定 key 的值。

未定义使用 key 值调用 pthread_setspecificpthread_getspecific (未从 pthread_key_create 中获取) 或在使用 pthread_key_delete 删除密钥之后调用该值的效果。

可以从特定于线程的数据析构函数调用 pthread_setspecificpthread_getspecific 。 但是,从析构函数调用 pthread_setspecific 可能会导致丢失存储器或无限循环。

参数

描述
key 指定值绑定到的键。
value 指定新的特定于线程的值。

返回值

函数 pthread_getspecific 返回与给定键关联的特定于线程的数据值。 如果没有特定于线程的数据值与键相关联,那么将返回值 NULL。 如果成功,那么 pthread_setspecific 函数将返回零。 否则,将返回错误号以指示错误。

错误代码

在下列情况下, pthread_setspecific 函数将失败:

描述
ENOMEM 内存不足,无法将值与键相关联。

在下列情况下, pthread_setspecific 函数可能失败:

描述
EINVAL 键值无效。

未从 pthread_getspecific返回任何错误。

这些函数不会返回错误代码 EINTR。