capypad
0 day streak
rust / intermediate
Snippet

Using Arc for Thread-Safe Shared Ownership

Arc (Atomic Reference Counting) provides shared ownership across multiple threads. Unlike Rc which is single-threaded only, Arc uses atomic operations for its reference count, making it safe to share between threads. For mutable access, combine Arc with Mutex or RwLock.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use std::sync::Arc;
use std::thread;
 
struct Config {
api_url: String,
timeout_secs: u64,
}
 
fn main() {
let config = Arc::new(Config {
api_url: String::from("https://api.example.com"),
timeout_secs: 30,
});
 
let handles: Vec<_> = (0..3).map(|i| {
let config = Arc::clone(&config);
thread::spawn(move || {
println!("Thread {} using API: {}", i, config.api_url);
})
}).collect();
 
for handle in handles {
handle.join().unwrap();
}
}
Breakdown
1
use std::sync::Arc;
Imports Arc for atomic reference counting
2
let config = Arc::new(Config { ... });
Creates Arc-wrapped Config shared between threads
3
let config = Arc::clone(&config);
Increments reference count, cheap pointer clone
4
thread::spawn(move || { ... })
Spawns thread that moves cloned Arc into closure
5
handle.join().unwrap();
Waits for all threads to complete