操作系统原理 2026

thread_local:每个线程一份变量

原片 01:06:22—01:08:30

sum_local 的数组写法不太好看:每次都要 sum_local[tid],sum += sum_local[tid],再置为 0。操作系统和语言设计者也不喜欢,因此有了 thread_local keyword,从 C++11 开始支持。

C23 也正式支持,C 中可以直接写 thread_local,以前用 __thread。线程创建时,每个 thread_local 变量自动得到一份拷贝,类型可以是 struct。

图 54:thread_local:每个线程一份变量(01:07:05)。
图 54:thread_local:每个线程一份变量(01:07:05)。

课件中的 thread_local 示例,保留标作编译错误的局部声明:

thread_local int sum_local;

void T_sum() {
  thread_local int t;  // Compile error
  sum_local++;        // 每个线程有自己的 sum_local
}

也可以是指针,并可赋初值。只需定义 thread_local int sum_local,T_sum 里就能使用各自那份。若在函数或代码块等非全局作用域定义 thread_local int,编译器会直接报错。thread_local 要求每线程一份,定义在 T_sum 中却意味着每次函数调用、每个栈帧一份。

这两个含义冲突,所以会报错。再看 thread_local int x 等 100,线程中做 x 加加。若写成普通 int x 等 100,就会有 data race,可能看到 101、102、103、104;thread_local int 应看到四个 101。这里还对 x 取地址。

图 55:线程局部变量的演示代码(01:08:10)。
图 55:线程局部变量的演示代码(01:08:10)。

tls.c 演示使用课程的 thread.h 与 thread-sync.h:

#include <thread.h>
#include <thread-sync.h>

thread_local int x = 100;

void T_worker(int tid) {
  // thread_local int y;  // Not compile.
  x++;
  printf("Thread %d: %p = %d\n", tid, &x, x);
}

int main() {
  for (int i = 0; i < 4; i++) {
    spawn(T_worker);
  }
}

第十行取出 x 的地址,每个 T_worker 应看到不同地址。可以相信编译器,也可以看演示:线程 1234 打印的地址不同,加 1 后值都为 101。

输入关键词,搜索全部 30 节课。