Skip to content
เข้าสู่ระบบ

Concurrency Traits

Thread safety traits

use std::thread;
use std::sync::Arc;
use std::rc::Rc;
fn main() {
// Send = safe to SEND to another thread
// Ownership can be transferred across thread boundaries
// Owned data is Send if type is Send
let data = vec![1, 2, 3, 4, 5];
let handle = thread::spawn(move || {
// data is moved here
println!("Vec in thread: {:?}", data);
});
handle.join().unwrap();
// Arc is Send (when T: Send + Sync)
let shared = Arc::new(String::from("shared"));
let shared_clone = Arc::clone(&shared);
thread::spawn(move || {
println!("Arc in thread: {}", shared_clone);
}).join().unwrap();
// Rc is NOT Send
let rc = Rc::new(42);
// thread::spawn(move || { println!("{}", rc); }); // Error!
println!("\nRc must stay single-threaded: {}", rc);
println!("\n=== Send Types ===");
println!("- i32, String, Vec<T> where T: Send");
println!("- Arc<T> where T: Send + Sync");
println!("- Mutex<T> where T: Send");
println!("- mpsc::Sender<T> where T: Send");
println!("\n=== NOT Send ===");
println!("- Rc<T>: non-atomic refcount");
println!("- Raw pointers: *const T, *mut T");
println!("- MutexGuard: must unlock in same thread");
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด