Borrow rule confusion, regarding mutability

From what I gather, a mutable borrow cannot occur when there's an existing immutable borrow exists, and vice versa. However, in multithreaded code (ie. servers), this seems necessary, hence why mutexes, locks, etc exist. I mean, eventually borrowed data will have to be modified. If I use a mutex to ensure no data races, what's the problem exactly?

None, that's why Mutex is safe. It's just non-trivial to prove correctness in general, so it is not the default. Also think of &mut T is a unique borrow of T, and &T as a shared borrow of T. This is closer to how the compiler thinks of references.

read more here:

Another thing to note is the Rust likes to be upfront about costs, hence why you must use Mutex explicitly (similarly with Box or Arc).


Ooo, that was an interesting read! As for stuff like networking, I'm guessing the MPSC's transmitter/receiver structure allows a sort of broadcast mechanism, say for a chatroom? (ie. transmit a message, every receiver for it gets that message?)

Well, it's a bit backward, you can send from multiple produces, but only have one consumer at a time

(altough it would be much better for you to use crossbeam's channels, as it is better in basically every way)

I know Tokio has channels also. Would Crossbeam's still be better?

If you are using async, use tokio's channels, as they are integrated with the tokio runtime. If you are doing ordinary blocking, use crossbeam's channels.

1 Like

Async, but thanks for the info.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.