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)); }