Card 1 / 4
round_trip moves a value into a new thread and hands it straight back. Add the trait bounds T needs so it compiles.
value |
round_trip(value) |
exercises |
|---|---|---|
42i32 |
42 |
a Copy scalar |
String::from("hi") |
String::from("hi") |
an owned heap type |
vec![1, 2, 3] |
vec![1, 2, 3] |
an owned collection |
Send marks a type that is safe to move to another thread. thread::spawn additionally requires 'static: the spawned closure may outlive the caller, so it must not hold anything borrowed from it.
/// Spawn a thread that takes ownership of `value` and returns it.
/// Add the trait bounds T needs so it can be moved into a thread.
fn round_trip<T
: Send + 'static
>(value: T) -> T {
thread::spawn(move || value).join().unwrap()
}Card 2 / 4
Send means a value may be moved to another thread; Sync means a &T may be shared with another thread. Rc<T> is neither, while Arc<T> is both. Why the difference?