15 Comments
User's avatar
Rust Bytes's avatar

This is a very good writeup on Send and Sync, we'd love to include it in the upcoming issue of our newsletter!

Expand full comment
Cuong Le's avatar

Thanks! That's awesome. Really appreciate you including it!

Expand full comment
cauldron's avatar

This was fun and very useful, thank you. I will likely re-read it in a few days.

Just one question: An `Arc<Mutex<T>>` allows us to modify the data `T` safely, from multiple threads, right? So besides the "safe shared-state of Arc" there is the data-modification-safety. Plus, we retain ownership of `T` in the main thread I think.

Expand full comment
Cuong Le's avatar

Hi, thanks for reading!

Yes, Arc<Mutex<T>> allows you to modify the data T safely from multiple threads. Because Mutex ensures only one thread can access the inner data at any given moment, preventing data races.

However, you don't exactly "keep ownership in the main thread". Instead, you have almost like a "shared ownership" across all threads that hold a clone of the Arc. All Arc clones point to the same underlying Mutex. The main thread is just one of the threads that keeps ownership of the Arc.

Hope it helps!

Expand full comment
cauldron's avatar

It does help. Thanks!

Expand full comment
coderock's avatar

looking forward a deeper explanation of interior mutability and why Rust needs it

Expand full comment
Cuong Le's avatar

@coderock: Interior mutability was another one of those "why does this exist?" moments for me. The whole "one mutable OR multiple shared references" rule feels so fundamental when learning Rust - then interior mutability comes along and breaks it! But this is for a good reason. Definitely planning a post on that!

Expand full comment
Jacob Zimmerman's avatar

All I really needed from you was the bit that the book says, which finally explained to me why the heck they have the names that they do, which helped me finish wrapping my head around the rest, though the rest of what you wrote helped cement it, I think.

Expand full comment
thyrotoxicoses's avatar

Similar article is in "Rust Atomics and Locks" https://marabos.nl/atomics/basics.html#thread-safety

Expand full comment
Cuong Le's avatar

Thanks for sharing. Though I found those definitions-focused approaches were exactly what left me confused for months :) That's why I focused on the underlying thread safety principles instead.

Expand full comment
Cuong Le's avatar

Interesting! Thanks for sharing.

Expand full comment
Kilian Hammersmith's avatar

This is a great discussion around the internals and Send and Sync. Like you to this point I have read statements like Send can be sent across threads and Sync can be shared across threads but I never really understood why. Much clearer now thank you

Expand full comment
Cuong Le's avatar

Thanks! That's exactly the problem I was trying to solve - knowing what but not why. Glad it made more sense!

Expand full comment