rust concurrency_error ai_generated true

error[E0277]: `X` cannot be sent between threads safely

ID: rust/e0277-send-not-satisfied

Also available as: JSON · Markdown
85%Fix Rate
90%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

Type doesn't implement Send trait. Can't use across threads. Common with Rc, RefCell.

generic

Workarounds

  1. 95% success Use Arc instead of Rc for shared ownership across threads
    use std::sync::Arc;
    let shared = Arc::new(data);

    Sources: https://doc.rust-lang.org/std/sync/struct.Arc.html

  2. 92% success Use Mutex/RwLock instead of RefCell for interior mutability across threads
    use std::sync::Mutex;
    let data = Arc::new(Mutex::new(value));

    Sources: https://doc.rust-lang.org/std/sync/struct.Mutex.html

  3. 85% success If using async, ensure futures are Send by avoiding non-Send types across .await
    // Rc is not Send. Use Arc instead:
    use std::sync::Arc;
    let shared = Arc::new(data);
    
    // RefCell is not Send. Use Mutex instead:
    use std::sync::Mutex;
    let shared = Arc::new(Mutex::new(data));
    
    // Ensure no non-Send types are held across .await:
    let result = {
        let guard = mutex.lock().unwrap();
        guard.clone() // clone before .await
    };
    some_async_fn().await;

    Sources: https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html

Dead Ends

Common approaches that don't work:

  1. Implement Send with unsafe impl 95% fail

    Implementing Send unsafely on types that aren't thread-safe causes UB

  2. Use single-threaded runtime 55% fail

    Limits application scalability unnecessarily

Error Chain

Frequently confused with: