Thread Local Values With RefCell

thread_local! gives each thread its own RefCell-backed value, so counters started in a spawned thread begin from zero instead of sharing main's state.

RustData Integrity

Code

rustsnippet
26 lines
use std::cell::RefCell;

thread_local! {
    // 每个线程独享一份:内部可变性靠 RefCell 承担,互不干扰
    static CALLS: RefCell<u64> = RefCell::new(0);
}

fn track() -> u64 {
    CALLS.with(|calls| {
        *calls.borrow_mut() += 1;
        *calls.borrow()
    })
}

fn main() {
    println!("main first: {}", track());
    println!("main second: {}", track());

    // 子线程拿到自己的一份副本:计数从 0 重新开始
    let handle = std::thread::spawn(|| {
        println!("child first: {}", track());
        track()
    });
    println!("child total: {}", handle.join().unwrap());
    println!("main still: {}", track());
}

How it works

The working surface is the functions track and main — everything else is wiring.

Putting it to use

The main signature reads fn track() -> u64

The demo output is labeled (main first:, main second:, child first:), so every printed line maps back to its originating operation.

The sequence track lives in main; running the file triggers it.

Core lines

fn track() -> u64 {
    CALLS.with(|calls| {
        *calls.borrow_mut() += 1;
        *calls.borrow()
    })
}

Interactive Tools for This Topic

FAQ

What does Thread Local Values With RefCell print when run?
Run it as a complete program — the output lines carry labels such as `main first:`, `main second:`, `child first:`.