1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
use crate::rand::Rand; use crate::source::RngSource; thread_local!( pub static THREAD_RAND: std::cell::RefCell<Rand<RngSource>> = std::cell::RefCell::new(Rand::new(RngSource::new(1))); ); pub struct ThreadLocal; impl ThreadLocal { pub fn seed(seed: i64) { THREAD_RAND.with(|x| { let x: &std::cell::RefCell<Rand<RngSource>> = x; let mut x = x.borrow_mut(); x.seed(seed); }) } pub fn int32() -> i32 { THREAD_RAND.with(|x| { let x: &std::cell::RefCell<Rand<RngSource>> = x; let mut x = x.borrow_mut(); x.int32() }) } pub fn uint32() -> u32 { THREAD_RAND.with(|x| { let x: &std::cell::RefCell<Rand<RngSource>> = x; let mut x = x.borrow_mut(); x.uint32() }) } pub fn int32n(n: i32) -> i32 { THREAD_RAND.with(|x| { let x: &std::cell::RefCell<Rand<RngSource>> = x; let mut x = x.borrow_mut(); x.int32n(n) }) } pub fn int64() -> i64 { THREAD_RAND.with(|x| { let x: &std::cell::RefCell<Rand<RngSource>> = x; let mut x = x.borrow_mut(); x.int64() }) } pub fn uint64() -> u64 { THREAD_RAND.with(|x| { let x: &std::cell::RefCell<Rand<RngSource>> = x; let mut x = x.borrow_mut(); x.uint64() }) } pub fn int64n(n: i64) -> i64 { THREAD_RAND.with(|x| { let x: &std::cell::RefCell<Rand<RngSource>> = x; let mut x = x.borrow_mut(); x.int64n(n) }) } pub fn shuffle<T>(array: &mut Vec<T>) { THREAD_RAND.with(|x| { let x: &std::cell::RefCell<Rand<RngSource>> = x; let mut x = x.borrow_mut(); x.shuffle(array); }) } } #[cfg(test)] mod test { use super::ThreadLocal; use std::thread; #[test] fn example_thread_local() { let mut handles = vec![]; for i in 0..4 { let h = thread::spawn(move || { for j in 0..3 { println!( "thread local: {}, index: {}, {}", i, j, ThreadLocal::int64() ); } }); handles.push(h); } for h in handles { h.join().unwrap(); } } }