1778

9 分钟

#C 语言标准库函数 tss_get

/********************************************* * @brief 读取线程局部存储的值 * @param tss 线程局部存储 ID ********************************************/ void* tss_get(tss_t tss);

说明

读取线程局部存储的值。

同一个程局部存储 ID 可在多个线程中使用,每个线程中绑定的值都是独立的。

参数

  • tss - 线程局部存储 ID

返回值

  • 线程局部存储的值
  • 失败时返回 NULL

#示例

#include <stdio.h> #include <threads.h> // 线程入口函数 int func(void* data) { // 通过参数传入 tss tss_t* tss = (tss_t*)data; // 读取线程局部存储值 printf("%p\n", tss_get(*tss)); // NULL // 子线程设置局部存储值 tss_set(*tss, (void*)"func"); printf("%s\n", (char*)tss_get(*tss)); // "func" return 0; } int main(void) { // 创建线程局部存储 tss_t tss; tss_create(&tss, NULL); // 主线程设置局部存储值 tss_set(tss, (void*)"main"); // 创建线程 thrd_t th; thrd_create(&th, func, &tss); // 通过参数传入 tss // 等待线程结束 thrd_join(th, NULL); // 读取线程局部存储值 printf("%s\n", (char*)tss_get(tss)); // "main" // 删除线程局部存储 // 这里只会清理 tss,但不会清理 ptr tss_delete(tss); return 0; }

运行结果

(nil) func main

说明

线程局部存储在每个线程中绑定的值都是独立的:

  • 主线程将值设为 "main",进入子线程中读取得到 NULL
  • 子线程将值设为 "func",返回主线程读取得到 "main"

#推荐阅读

#参考标准

  • C17 standard (ISO/IEC 9899:2018):
    • 7.26.6.3 The tss_get function (p: 282)
  • C11 standard (ISO/IEC 9899:2011):
    • 7.26.6.3 The tss_get function (p: 386)

创建于 2025/8/27

更新于 2025/8/27