usestd::thread;staticVAR:i32=5;fnmain(){// 创建一个新线程letnew_thread=thread::spawn(move||{println!("static value in new thread: {}",VAR);});// 等待新线程先运行new_thread.join().unwrap();println!("static value in main thread: {}",VAR);}
运行结果:
static value in new thread: 5
static value in main thread: 5
use std::thread;
static mut VAR: i32 = 5;
fn main() {
// 创建一个新线程
let new_thread = thread::spawn(move|| {
unsafe {
println!("static value in new thread: {}", VAR);
VAR = VAR + 1;
}
});
// 等待新线程先运行
new_thread.join().unwrap();
unsafe {
println!("static value in main thread: {}", VAR);
}
}
static value in new thread: 5
static value in main thread: 6
use std::thread;
use std::sync::Arc;
fn main() {
let var : Arc<i32> = Arc::new(5);
let share_var = var.clone();
// 创建一个新线程
let new_thread = thread::spawn(move|| {
println!("share value in new thread: {}, address: {:p}", share_var, &*share_var);
});
// 等待新建线程先执行
new_thread.join().unwrap();
println!("share value in main thread: {}, address: {:p}", var, &*var);
}
share value in new thread: 5, address: 0x2825070
share value in main thread: 5, address: 0x2825070
pub fn new(data: T) -> Arc<T> {
// Start the weak pointer count as 1 which is the weak pointer that's
// held by all the strong pointers (kinda), see std/rc.rs for more info
let x: Box<_> = box ArcInner {
strong: atomic::AtomicUsize::new(1),
weak: atomic::AtomicUsize::new(1),
data: data,
};
Arc { _ptr: unsafe { NonZero::new(Box::into_raw(x)) } }
}