Arc
当需要在线程之间共享所有权时,可以使用Arc
(原子引用计数)。这个结构体,通过 Clone
实现,可以为内存堆中某个值的位置创建一个引用指针,同时增加引用计数。由于它在线程之间共享所有权,当最后一个指向某个值的引用指针超出作用域时,该变量将被释放。
use std::time::Duration; use std::sync::Arc; use std::thread; fn main() { // This variable declaration is where its value is specified. let apple = Arc::new("the same apple"); for _ in 0..10 { // Here there is no value specification as it is a pointer to a // reference in the memory heap. let apple = Arc::clone(&apple); thread::spawn(move || { // As Arc was used, threads can be spawned using the value allocated // in the Arc variable pointer's location. println!("{:?}", apple); }); } // Make sure all Arc instances are printed from spawned threads. thread::sleep(Duration::from_secs(1)); }