Fix a spawned closure that is rejected because it captures a type that is not Send
A worker thread fills a Report and returns its text. The build fails with error[E0277]: `Rc<str>` cannot be sent between threads safely. Report comes from a library you cannot change. Make the program compile.
Requirements:
- Leave
Reportuntouched. - No
Arc, noMutex, nounsafe. - The worker thread still adds the lines; the output is
squares: 1, 4, 9.
use std::rc::Rc;
use std::thread;
struct Report {
title: Rc<str>,
lines: Vec<String>,
}
impl Report {
fn render(&self) -> String {
format!("{}: {}", self.title, self.lines.join(", "))
}
}
fn main() {
let mut report = Report {
title: Rc::from("squares"),
lines: Vec::new(),
};
let h = thread::spawn(move || {
for n in 1..=3 {
report.lines.push((n * n).to_string());
}
report.render()
});
println!("{}", h.join().unwrap());
}Find and fix the bug.
Report holds an Rc<str>, so it is not Send and cannot move into the thread (E0277). Move only Send inputs, the title as a String, build the Report inside the closure and return the rendered String; the Rc never crosses threads.
- Reaching for
Arc<Mutex<T>>by reflex when the value never needs to be shared, only built on the right thread - Believing a fresh clone of an
Rc-holding value becomesSend, though the type, not the instance, decides - Silencing E0277 with
unsafe impl Send, which promises a thread safety the non-atomic count cannot keep
- How would you keep the
Reporton one thread and feed it lines from several workers instead? - Why is a
RefCellmoved into a thread whole accepted while anRcis not?
thread::spawn requires the closure to be Send, and a closure is Send only if everything it captured is Send. Report is auto-derived as not Send: one of its fields is an Rc<str>. But Report does not have to cross the thread boundary at all: the worker needs only the title, and main needs only the finished text. Both are a String, and String is Send:
use std::rc::Rc;
use std::thread;
struct Report {
title: Rc<str>,
lines: Vec<String>,
}
impl Report {
fn render(&self) -> String {
format!("{}: {}", self.title, self.lines.join(", "))
}
}
fn main() {
let title = String::from("squares"); // String is Send
let h = thread::spawn(move || {
let mut report = Report {
title: Rc::from(title.as_str()), // the Rc is born on this thread
lines: Vec::new(),
};
for n in 1..=3 {
report.lines.push((n * n).to_string());
}
report.render() // only the String leaves the thread
});
println!("{}", h.join().unwrap()); // squares: 1, 4, 9
}The same trick works for any non-Send resource, such as handles built on Rc, RefCell or raw pointers: you send into the thread what the resource is built from, and get the result back. If a non-Send value must live long and serve several threads, it stays on one owner thread and the others send it messages over a channel. Arc<Mutex<T>> would not have helped here at all: Mutex<T> is itself Send only when T: Send.