KRAZY感情TEXTYLE

"くれいじー かんじよう てきしたいる" と読みます

thread_localメモ

自分用覚書、thread_local!で定義したstatic変数はスレッド毎に LocalKeyという構造体でwrapされる。各スレッド変数はそれぞれ外側に不変である、可変参照をしたいならRefCellを被せたりする。

use std::cell::RefCell;

thread_local! {
    static X: RefCell<Vec<usize>> = RefCell::new(vec![]);
}

fn main() {
    X.with(|v| {
        println!("initial {:?}", v.borrow());
    });

    let j = std::thread::spawn(move || {
        X.with(|v| {
            v.borrow_mut().push(1000);
            println!("other thread {:?}", v.borrow());
        });
    });
    j.join().unwrap();
    X.with(|v| {
        println!("after other thread {:?}", v.borrow());
        v.borrow_mut().push(1024);
    });

    main_other_fn();
}

fn main_other_fn() {
    X.with(|v| {
        println!("main_other_fn {:?}", v.borrow());
    });
}

initial
other thread [1000]
after other thread

main_other_fn [1024]