Arc
Arc<T>
allows shared read-only access via Arc::clone
:
use std::thread; use std::sync::Arc; fn main() { let v = Arc::new(vec![10, 20, 30]); let mut handles = Vec::new(); for _ in 1..5 { let v = Arc::clone(&v); handles.push(thread::spawn(move || { let thread_id = thread::current().id(); println!("{thread_id:?}: {v:?}"); })); } handles.into_iter().for_each(|h| h.join().unwrap()); println!("v: {v:?}"); }
Arc
significa âAtomic Reference Countedâ, uma versĂŁo thread-safe deRc
que usa operaçÔes atÎmicas.Arc<T>
implementsClone
whether or notT
does. It implementsSend
andSync
if and only ifT
implements them both.Arc::clone()
tem o custo das operaçÔes atÎmicas que são executadas, mas depois disso o uso doT
Ă© gratuito.- Cuidado com os ciclos de referĂȘncia,
Arc
nĂŁo usa um coletor de lixo para detectĂĄ-los.std::sync::Weak
pode ajudar.