/*********************************************
* @brief 读取线程局部存储的值
* @param tss 线程局部存储 ID
********************************************/
void* tss_get(tss_t tss);
!subtitle:说明
读取线程局部存储的值。
同一个程局部存储 ID 可在多个线程中使用,每个线程中绑定的值都是独立的。
!subtitle:参数
tss - 线程局部存储 ID
!subtitle:返回值
线程局部存储的值
失败时返回 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;
}
!subtitle:运行结果
(nil)
func
main
!subtitle:说明
线程局部存储在每个线程中绑定的值都是独立的:
主线程将值设为 "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)