---
title: HTL_thread_key_create
description: "创建线程私有变量。"
url: https://www.hikunpeng.com/document/detail/zh/kunpengboostkithistory/251RC1/accel/kunpengaccel_ksl_16_0142.html
sourcePath: /source/zh/kunpengboostkithistory/251RC1/accel/kunpengaccel_ksl_16_0142.html
indexId: 03c55adb922c53cbf02e2b7b5a4167ea8dd35572b817a2872b137cbf9ec784c976
---
# HTL_thread_key_create

创建线程私有变量。

#### 接口定义

int HTL_thread_key_create(void (*destructor)(void *value), HTL_thread_key_t *thread_key);


#### 描述

HTL_thread_key_create()用于创建一个类型为HTL_thread_key_t的线程私有变量thread_key。尽管不同线程可使用相同线程私有变量thread_key，但通过函数HTL_thread_setspecific()设置thread_key的值在不同线程是不同的。

创建线程私有变量时，使用NULL值关联新的线程私有变量thread_key，并与其所有现有线程中的线程私有变量thread_key相关联。当创建新的线程时，将使用NULL值关联所有定义的线程私有变量thread_key。

析构函数destructor()是可选的，注册给线程私有变量thread_key。当线程退出时，如果线程私有变量非NULL，此函数会自动被调用。

创建的线程私有变量thread_key在使用后必须由函数HTL_thread_key_delete()释放。


#### 参数

| 参数名 | 类型 | 描述 | 输入/输出 |
| --- | --- | --- | --- |
| destructor | void (\*destructor)(void \*value) | 析构函数。 | 输入 |
| thread\_key | HTL\_thread\_key\_t \* | 线程私有变量句柄地址。 | 输出 |


#### 返回值

- HTL_THREAD_SUCCESS：成功。
- 其他：失败。见错误码定义。


#### 示例

```
int ret;
    static HTL_thread_key_t tls[NUM_TLS];
    ret = HTL_thread_key_create(NULL, &tls[i]);
```
