Thread-Local Storage (TLS)

TLS 讓每個 thread 擁有某個變數的獨立副本,彼此完全隔離,是解決 multi-threaded 程式中 per-thread state 問題的標準手段。

動機

在 multi-threaded 程式裡,所有 thread 共享同一塊 heap 和 global 變數,但有時候你需要某個變數「每個 thread 各自有一份、互不干擾」,例如每個 thread 自己的 error code、random seed、或 connection handle

// 一般 global 變數:所有 thread 共享同一份
int counter = 0;
 
// TLS 變數:每個 thread 各自有一份獨立的 counter
__thread int counter = 0;

TLS vs. Local Variable vs. Static Variable

Local VariableStatic VariableTLS
生命週期單次 function call整個 process整個 thread
跨 function call 存活?
每個 thread 獨立?✅(天然)❌ 共享

TLS 可以理解為「per-thread 的 static variable」——像 static 一樣跨越多次 function call 持久存在,但像 local variable 一樣對每個 thread 是私有的。

在 Thread Pool 中的重要性

thread pool 的情境下,worker thread 不是你自己建立的,你無法在建立時傳入 per-thread 的初始狀態。TLS 因此成了讓每個 worker 保有自己私有狀態的唯一方式,不需要任何 lock,也不會有 race condition。