skip to content

Why does rustc reject moving even the only `Rc<Vec<i32>>` into `thread::spawn`, and what in `Rc` makes it neither `Send` nor `Sync`?

level: middleimportance: should knowfreq 55%

answer

  1. E0277 at the spawn call
  2. Cell<usize> counts in the allocation
  3. non-atomic increment and decrement
  4. checked on the type, not the count
  5. unwrap first, then send the T

basics

~20 s

Rc keeps its strong and weak counts in plain Cell<usize> fields updated without atomics, so std declares Rc and Weak !Send and !Sync for every T. rustc checks the type, not the run-time count, so even a sole handle fails with E0277.

solid answer

~50 s

`thread::spawn` requires its closure to be `Send + 'static`, and a closure that captures an `Rc<Vec<i32>>` is not `Send`, so rustc stops with E0277: `Rc<Vec<i32>>` cannot be sent between threads safely. The reason is inside `Rc`: the strong and weak counts are `Cell<usize>` fields bumped with ordinary, non-atomic read-modify-write. Two threads cloning or dropping handles to one allocation at once could lose an update and free the value while it is still in use. So std writes `impl !Send for Rc` and `impl !Sync for Rc` for every `T`, and the same for `std::rc::Weak`. The check is on the type, so a handle whose count happens to be 1 is rejected too. If you really hold the only one, take the value out with `Rc::try_unwrap` and send the `Vec`; to share across threads, use `Arc`, the atomic counterpart.

code

rust · 8 lines
rust
use std::rc::Rc;
use std::thread;

fn main() {
    let shared = Rc::new(vec![1, 2, 3]);
    let handle = thread::spawn(move || println!("{:?}", shared));
    handle.join().unwrap();
}

go deeper

for a junior

Recall that Rc cannot be moved into thread::spawn, that rustc says so with E0277, and that Arc is the thread-safe counterpart.

for a middle

Explain that Rc's counts are Cell fields updated without atomics, why std marks Rc and Weak neither Send nor Sync for every T, and why a sole handle is still rejected.

for a senior

Show the escape routes in order of cost: try_unwrap and send the value, a scoped borrow, or Arc, and spot an Rc held across an await that makes a future impossible to spawn.

for a principal

Argue the cost of defaulting to Arc everywhere against keeping single-threaded code on Rc, where cheaper counts and a compile-time thread boundary are the gain.

## The error `std::thread::spawn` has the bound `F: Send + 'static` on its closure. A `move` closure that captures an `Rc<Vec<i32>>` contains that `Rc`, and a closure is `Send` only if everything it captures is. rustc 1.99.1 reports it like this (trimmed): ```plaintext error[E0277]: `Rc<Vec<i32>>` cannot be sent between threads safely = help: within `{[email protected]:6:32: 6:39}`, the trait `Send` is not implemented for `Rc<Vec<i32>>` note: required by a bound in `spawn` ``` Three things are worth reading in it: - the **E-code**, E0277, which is rustc's general unsatisfied-trait-bound error; - the **help line**, which names the missing trait, `Send`, and the type that lacks it; - the **note**, which points at the `F: Send + 'static` bound on `spawn`. The first code example below is the exact program; it is rejected even though `shared` is the only handle and is moved, not borrowed. ## What inside `Rc` is unsafe to share An `Rc` handle is a pointer to a heap block holding the value and two counts. In the standard library source that block is - `strong: Cell<usize>`, the number of `Rc` handles, - `weak: Cell<usize>`, tracking the `Weak` handles, - `value: T`. `Rc::clone` reads the strong count, adds one and writes it back; dropping a handle reads, subtracts one and writes back. These are **plain loads and stores**, not atomic instructions. That is why `Rc` is cheap, and also why it must stay on one thread. If two threads could hold handles to the same block: 1. both read a strong count of 2; 2. both drop their handle and write 1; 3. the count says 1 while no handle exists, so the value leaks. A clone racing a drop can do the opposite: the count reaches 0 while a handle still exists, and the value is **freed while in use**. The second outcome is a use-after-free, which safe Rust must never allow. So std opts `Rc` out of both thread-safety marker traits explicitly: | Type | `Send` | `Sync` | Why | |---|---|---|---| | `std::rc::Rc<T>` | no, for any `T` | no, for any `T` | non-atomic counts, `impl !Send` and `impl !Sync` in std | | `std::rc::Weak<T>` | no | no | shares the same counts, same negative impls | | `Vec<i32>` | yes | yes | no shared counters | | `std::sync::Arc<T>` | when `T: Send + Sync` | when `T: Send + Sync` | atomic counts, covered with the threads material | A source comment in `rc.rs` notes that the `!Sync` impl is not strictly needed for correctness, because `Rc` already contains a `Cell`, which is not `Sync`; it is written out for documentation and clearer error messages. ## Why a sole handle is still rejected `Send` is a property of a **type**, decided at compile time. rustc does not know the run-time strong count, and even a count of 1 does not mean the allocation is unshared: a `Weak` left on the first thread could `upgrade` at the same moment the new thread drops its handle, which is exactly the race above. A type that is sometimes safe to send cannot be `Send`. ## Fixes, depending on what you actually need 1. **You own the only strong handle and just want the data on another thread.** Move the value out: `Rc::try_unwrap(rc)` returns `Ok(T)` when the strong count is 1, and a `Vec<i32>` is `Send`. The second code example does this. `Rc::unwrap_or_clone` works too when a copy is acceptable. 2. **Several threads must share the value.** Replace `Rc` with `std::sync::Arc`, whose counts are atomic; its locking companions belong to the material on threads and locks. 3. **The thread only needs to read while the owner waits.** Pass the data by reference into a scoped thread, so no `Rc` crosses at all. The same rule reaches async code: a future that keeps an `Rc` alive across an `.await` is not `Send`, so a work-stealing runtime will not spawn it, a point covered with Send futures. ## What the restriction buys The thread boundary costs nothing at run time: rustc enforces it, so `Rc` can use the cheapest possible counter updates with no risk of a data race. Single-threaded code, such as a UI tree, an interpreter's object graph or a game's per-frame scene data, gets shared ownership without paying for atomic instructions on every clone and drop. Code that does cross threads is forced to say so in its types by choosing `Arc`, and a later change that tries to move an `Rc` into a thread fails at compile time instead of corrupting a count in production.

  • Is `Rc<T>` `Send` when `T` is `Send + Sync`, say `Rc<i32>`?
    No. The negative impls are written for every `T`, because the problem is `Rc`'s own counters, not the value. `Box<i32>` and `Vec<i32>` are `Send` because they have no shared counter; `Rc<i32>` is never `Send`.
  • Why can't `Rc` just check at run time that its strong count is 1 before crossing threads?
    Because `Send` is checked on types at compile time, and `spawn` takes any closure, not a count. A strong count of 1 also ignores `Weak` handles that could `upgrade` on the original thread while the new one drops its handle. `Rc::try_unwrap` is the run-time check that does exist: it hands back a plain `T` you can send.

  • Moving the only Rc into a thread is fine because nothing else can touch it.
  • Rc<T> is Send whenever T is Send.
  • Wrapping the Rc in a RefCell makes it safe to send.
  • Sending a Weak instead of an Rc gets around the restriction.
  • Rc is not Send because its value lives on the creating thread's stack.