共享内存
共享内存
在消息传递之外,还存在一种广为人知的并发模型,那就是共享内存。其实如果不能共享内存,消息传递也是不能在不同的线程间传递消息,也谈不上在不同的线程间等待和通知了。共享内存是这一切得以发生的基础。如果查看源码,你会发现消息传递的内部实现就是借用了共享内存机制。相对于消息传递而言,共享内存会有更多的竞争,但是不用进行多次拷贝,在某些情况下,也需要考虑使用这种方式来处理。在
static
use std::thread;
static VAR: i32 = 5;
fn main() {
// 创建一个新线程
let new_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)) } }
}
通过上面的运行结果,我们也可以发现新建线程和主线程中打印的