The `Sync` bound nobody asked for

11 points by gendx


polywolf

What?

There are a couple factoids here that are correct:

I can see how this can be confusing at first, but both facts combine to produce correct behavior. The Sync requirement is needed. The title & muddied conclusion of the post suggest otherwise, which is wrong.

gendx

I'm not quite convinced by the Cell example without context.

The whole point of types in the std::cell family is to be able to mutate them via a &self (interior mutability). So it's fair that they aren't Sync - and if you want both interior mutability and Sync it's fair that you need a Mutex or similar.

But if you can pass around a &mut self at will, you shouldn't need any of these interior mutability wrappers in the first place!

So without a more concrete example, I think the title could have been "The Cell nobody asked for". And indeed, it's quite common to tell Rust beginners to just "Arc<Mutex<_>> and chill" to not have to worry about the borrow checker. But if you're at a stage where performance matters and you indeed could have afforded to pass around a &mut self, it's time to remove the cell/mutex and "fight the borrow checker" a bit. Or use a non-work-stealing async runtime that doesn't send things across threads. Or any other applicable optimization.