线程局部存储 thread_local ​

核心概念 ​

线程局部存储(Thread-Local Storage,TLS)是一种机制,让每个线程拥有某个变量的独立副本。在 Rust 中通过 thread_local! 宏来声明线程局部变量。每个线程第一次访问该变量时会独立初始化一份,各线程对它的读写互不干扰,不需要加锁。线程局部变量的类型是 LocalKey<T>,通过 with() 方法和闭包来访问,闭包接收 &T 引用。由于每个线程有自己的副本,线程局部变量天然是线程安全的。

rust
use std::cell::RefCell;
use std::thread;

// 声明线程局部变量
thread_local! {
    // 每个线程有自己独立的计数器
    static COUNTER: RefCell<u32> = RefCell::new(0);
}

fn increment() {
    COUNTER.with(|c| {
        *c.borrow_mut() += 1;
    });
}

fn get_count() -> u32 {
    COUNTER.with(|c| *c.borrow())
}

fn main() {
    // 主线程递增 3 次
    increment();
    increment();
    increment();
    println!("主线程计数: {}", get_count());  // 3

    // 子线程有自己的计数器副本(从 0 开始)
    let handle = thread::spawn(|| {
        println!("子线程初始: {}", get_count());  // 0
        increment();
        increment();
        println!("子线程计数: {}", get_count());  // 2
    });
    handle.join().unwrap();

    // 主线程的计数器不受影响
    println!("主线程仍然: {}", get_count());  // 3
}

thread_local 的声明方式 ​

rust
use std::cell::{Cell, RefCell};

// 声明多个线程局部变量
thread_local! {
    // 简单类型用 Cell
    static ID: Cell<u64> = Cell::new(0);

    // 复杂类型用 RefCell
    static NAME: RefCell<String> = RefCell::new(String::from("匿名"));

    // 可以用 const 初始化(编译期常量,性能更好)
    static MAX_RETRY: Cell<u32> = const { Cell::new(3) };

    // Vec 等集合类型
    static LOG_BUFFER: RefCell<Vec<String>> = RefCell::new(Vec::new());
}

fn main() {
    // 用 with 访问
    ID.with(|id| id.set(1001));
    NAME.with(|name| *name.borrow_mut() = "张三".to_string());
    LOG_BUFFER.with(|buf| buf.borrow_mut().push("初始化完成".to_string()));

    // 读取
    ID.with(|id| println!("ID: {}", id.get()));
    NAME.with(|name| println!("名称: {}", name.borrow()));
    MAX_RETRY.with(|max| println!("最大重试: {}", max.get()));
    LOG_BUFFER.with(|buf| println!("日志: {:?}", buf.borrow()));
}

Cell 和 RefCell 在 thread_local 中的角色 ​

rust
use std::cell::{Cell, RefCell};
use std::thread;

thread_local! {
    // Cell:适合 Copy 类型,get/set 操作
    static COUNTER: Cell<i32> = Cell::new(0);

    // RefCell:适合非 Copy 类型,需要可变借用
    static DATA: RefCell<Vec<i32>> = RefCell::new(Vec::new());
}

fn main() {
    // Cell 的用法
    COUNTER.with(|c| c.set(c.get() + 1));
    COUNTER.with(|c| c.set(c.get() + 1));
    COUNTER.with(|c| println!("Cell 计数: {}", c.get()));

    // RefCell 的用法
    DATA.with(|d| d.borrow_mut().push(10));
    DATA.with(|d| d.borrow_mut().push(20));
    DATA.with(|d| println!("RefCell 数据: {:?}", d.borrow()));

    // 子线程有独立的副本
    thread::spawn(|| {
        COUNTER.with(|c| println!("子线程 Cell: {}", c.get()));   // 0
        DATA.with(|d| println!("子线程 RefCell: {:?}", d.borrow())); // []
    }).join().unwrap();
}
内部可变性类型适用场景操作方式性能
Cell<T>Copy 类型(i32, f64, bool等)get() / set()更快
RefCell<T>非 Copy 类型(String, Vec等)borrow() / borrow_mut()运行时借用检查

thread_local 的生命周期 ​

rust
use std::cell::RefCell;
use std::thread;

thread_local! {
    static RESOURCE: RefCell<String> = RefCell::new({
        println!("  [初始化] 线程 {:?}", thread::current().id());
        String::from("资源已创建")
    });
}

fn main() {
    println!("=== 线程局部变量的生命周期 ===");

    // 主线程首次访问时初始化
    println!("主线程首次访问:");
    RESOURCE.with(|r| println!("  值: {}", r.borrow()));

    // 再次访问不会重新初始化
    println!("主线程再次访问:");
    RESOURCE.with(|r| println!("  值: {}", r.borrow()));

    // 每个子线程独立初始化
    let mut handles = Vec::new();
    for i in 0..3 {
        handles.push(thread::spawn(move || {
            println!("线程 {} 首次访问:", i);
            RESOURCE.with(|r| {
                let mut val = r.borrow_mut();
                *val = format!("线程{}的资源", i);
                println!("  值: {}", val);
            });
            // 线程结束时,线程局部变量被自动销毁
        }));
    }

    for h in handles {
        h.join().unwrap();
    }

    // 主线程的值不变
    println!("主线程最终:");
    RESOURCE.with(|r| println!("  值: {}", r.borrow()));
}

基本示例 ​

用 thread_local 实现线程级别的日志收集器和请求上下文:

rust
use std::cell::RefCell;
use std::thread;
use std::time::Duration;

// 线程级日志缓冲区
thread_local! {
    static LOG_BUFFER: RefCell<Vec<String>> = RefCell::new(Vec::new());
    static REQUEST_ID: RefCell<Option<String>> = RefCell::new(None);
}

// 设置当前线程的请求 ID
fn set_request_id(id: &str) {
    REQUEST_ID.with(|r| *r.borrow_mut() = Some(id.to_string()));
}

// 获取当前线程的请求 ID
fn get_request_id() -> String {
    REQUEST_ID.with(|r| {
        r.borrow().clone().unwrap_or_else(|| "unknown".to_string())
    })
}

// 写入线程本地日志
fn log(message: &str) {
    let req_id = get_request_id();
    let entry = format!("[{}] {}", req_id, message);
    LOG_BUFFER.with(|buf| {
        buf.borrow_mut().push(entry);
    });
}

// 刷新并返回日志
fn flush_logs() -> Vec<String> {
    LOG_BUFFER.with(|buf| {
        let logs = buf.borrow().clone();
        buf.borrow_mut().clear();
        logs
    })
}

fn handle_request(request_id: &str, user: &str) {
    set_request_id(request_id);
    log(&format!("收到来自 {} 的请求", user));

    // 模拟处理步骤
    log("验证身份");
    thread::sleep(Duration::from_millis(50));
    log("查询数据库");
    thread::sleep(Duration::from_millis(80));
    log("生成响应");

    let logs = flush_logs();
    println!("--- 请求 {} 的日志 ---", request_id);
    for entry in &logs {
        println!("  {}", entry);
    }
}

fn main() {
    let mut handles = Vec::new();

    // 模拟多个并发请求,每个在独立线程中
    let requests = vec![
        ("REQ-001", "张三"),
        ("REQ-002", "李四"),
        ("REQ-003", "王五"),
    ];

    for (req_id, user) in requests {
        let req_id = req_id.to_string();
        let user = user.to_string();
        handles.push(thread::spawn(move || {
            handle_request(&req_id, &user);
        }));
    }

    for h in handles {
        h.join().unwrap();
    }

    // 主线程的日志缓冲区是空的(独立的)
    let main_logs = flush_logs();
    println!("\n主线程日志: {} 条", main_logs.len());

    // === 线程局部的统计计数器 ===
    use std::cell::Cell;

    thread_local! {
        static OPS_COUNT: Cell<u64> = Cell::new(0);
    }

    fn do_operation() {
        OPS_COUNT.with(|c| c.set(c.get() + 1));
    }

    fn get_ops() -> u64 {
        OPS_COUNT.with(|c| c.get())
    }

    println!("\n=== 线程局部计数器 ===");
    let handles: Vec<_> = (0..4).map(|i| {
        thread::spawn(move || {
            // 每个线程执行不同次数的操作
            for _ in 0..(i + 1) * 100 {
                do_operation();
            }
            let count = get_ops();
            println!("  线程{}: {} 次操作", i, count);
            count
        })
    }).collect();

    let total: u64 = handles.into_iter()
        .map(|h| h.join().unwrap())
        .sum();
    println!("所有线程总计: {} 次操作", total);
}

常见问题 ​

问题一:thread_local 和全局变量有什么区别?

全局变量(static)是所有线程共享的,访问时需要同步(Mutex、RwLock 等)。线程局部变量每个线程有独立副本,不需要同步,不存在数据竞争。

问题二:thread_local 变量什么时候初始化?

惰性初始化——每个线程在第一次通过 with() 访问时才初始化。不同线程的初始化时机互相独立。

问题三:为什么要用 Cell/RefCell?

thread_local! 声明的变量通过 with() 只能拿到 &T(不可变引用)。要修改值需要内部可变性,所以用 Cell(Copy 类型)或 RefCell(非 Copy 类型)。

问题四:线程局部变量什么时候销毁?

线程结束时自动销毁。但销毁顺序不确定,且在析构函数中访问其他线程局部变量可能导致 panic(如果那个变量已经被销毁了)。

适用场景 ​

  • 线程级缓存:每个线程维护自己的缓存
  • 请求上下文:Web 服务中每个请求的上下文信息
  • 日志缓冲:每个线程收集日志后批量输出
  • 性能计数器:无锁的线程级统计

注意事项 ​

  • 通过 with() 闭包访问,不能直接获取引用
  • 需要内部可变性(Cell 或 RefCell)才能修改
  • 每个线程独立初始化和销毁
  • 不能在线程之间共享线程局部变量的数据
  • 析构顺序不确定,析构函数中不要访问其他 thread_local
  • const { ... } 初始化可以避免运行时开销

总结 ​

thread_local! 宏声明的变量每个线程拥有独立副本,天然线程安全,不需要加锁。通过 with() 方法和闭包来访问,with() 提供 &T 引用。修改值需要 Cell(Copy 类型)或 RefCell(非 Copy 类型)提供内部可变性。变量在每个线程首次访问时惰性初始化,线程结束时自动销毁。典型用途包括线程级缓存、请求上下文、日志缓冲、性能计数器等场景。与全局 static 变量不同,线程局部变量各线程互不干扰,无数据竞争风险。