capypad
0 day streak
rust / intermediate
Snippet

Send and Sync Traits for Thread Safety

Send and Sync are marker traits that indicate thread safety properties. Types implementing Send can be transferred between threads. Types implementing Sync can be accessed from multiple threads simultaneously (&T is Send). RefCell is Send but NOT Sync—it enforces borrow checking at runtime.

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
use std::thread;
use std::sync::Arc;
use std::cell::RefCell;
 
fn main() {
let shared_data = Arc::new(RefCell::new(vec![1, 2, 3]));
 
let data_clone = Arc::clone(&shared_data);
let handle = thread::spawn(move || {
let mut data = data_clone.borrow_mut();
data.push(4);
println!("Thread modified: {:?}", data);
});
 
handle.join().unwrap();
println!("Main sees: {:?}", shared_data.borrow());
 
println!("i32 is Send: {}", std::marker::Send);
println!("i32 is Sync: {}", std::marker::Sync);
println!("RefCell<T> is Send: {}", std::marker::Send);
println!("RefCell<T> is Sync: {}", std::marker::Sync);
}
Breakdown
1
Arc::new(...)
Atomically reference counted; allows shared ownership across threads
2
RefCell<T>
Interior mutability; borrow checking happens at runtime
3
Arc::clone(&shared_data)
Increments reference count; cheap pointer copy
4
RefCell<T> is NOT Sync
Sync requires &T to be Send; RefCell only allows one borrower at a time
5
std::marker::Send/Sync
Compiler provides automatic implementations for basic types