/*********************************************
* @brief 设置线程局部存储的值
* @param tss 线程局部存储 ID
* @param value 要设置的值
********************************************/
int tss_set(tss_t tss, void* value);
!subtitle:说明
设置线程局部存储的值。
同一个程局部存储 ID 可在多个线程中使用,每个线程中绑定的值都是独立的。
!subtitle:参数
tss - 线程局部存储 ID
value - 要设置的值
!subtitle:返回值
成功时返回 thrd_success
失败时返回 thrd_error
#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.4 The tss_set function (p: 282-283)
C11 standard (ISO/IEC 9899:2011):
7.26.6.4 The tss_set function (p: 387)