






















C语言中的 thread_local(在C11标准中为 _Thread_local,通常建议使用 <threads.h> 中的 thread_local 宏)用于声明线程局部存储 (Thread-Local Storage, TLS) 变量。
这种变量在每个线程中都有一个独立的实例,线程之间互不干扰,即使它们共享同一个变量名,在多线程环境下使用它不仅是线程安全的,还避免了互斥锁带来的性能开销。
thread_local 的核心特性C11 标准引入了 _Thread_local 关键字。通常引入 <threads.h> (如果编译器支持) 或在 C23 标准中直接使用 thread_local。
#include <stdio.h>
#include <threads.h> // C11线程标准库
// 定义一个线程局部变量
thread_local int thread_specific_var = 0;
int main_thread_func(void* arg) {
thread_specific_var = 10; // 当前线程修改
printf("Thread %d: var = %d\n", (int)thrd_current(), thread_specific_var);
return 0;
}
int main() {
thrd_t t1, t2;
// 启动两个线程
thrd_create(&t1, main_thread_func, NULL);
thrd_create(&t2, main_thread_func, NULL);
// 等待线程结束
thrd_join(t1, NULL);
thrd_join(t2, NULL);
return 0;
}
在上面的示例中,如果 thread_local 没有被定义,两个线程会共享 thread_specific_var 并产生冲突。使用了 thread_local 后,每个线程会打印出各自的 10,互不干扰。
_Thread_local 或 #include <threads.h> 后的 thread_local。thread_local。__thread 关键字(static __thread int var;),它更早期且实现效率较高。static 或 extern。pthread_key 区别: thread_local 是一种语言层面的特性,使用起来更简单、更高效,不再需要像 pthread_key_create 那样处理 void* 指针和显式管理内存。一般,“标准方式”和“编译器扩展方式”区别:
| 特性 | _Thread_local (C11) | __thread (GNU/Clang) |
|---|---|---|
在多线程程序中,如果需要维护线程特有的状态(如错误码 errno、特定线程的日志缓存等),thread_local 是现代C语言(C11及以后)推荐的线程安全实现方式。
参考资料:
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。