Hello, I am starting to learn and play around with tokio and multithreaded code. I am now playing around with websockets, I don’t quite understand the difference between broadcast and mpsc, and when would you use either, I mean, I am assuming broadcast is intended for multiple clients, but multiple clients were able to connect to my mscp channel, and receive a bit of data (but it was weird and partial). So I don’t quite get it.
Weird thing is, is that. I only had one mscp in my app state, it was behind a arc mutex and code that accessed it was running asynchronously, but, somehow they all got the same messages for a bit, then like, stopped or got very partial messages except the intended recipient (they got the full message). Is this some memory issue, or race condition?
I don’t have this issue switching to broadcast but I’m confused
You don’t need to arc-mutex an mpsc. On the sender side, clone the sender as many times as you need and pass it by value (each sender owns a clone). On the receiver side you must have only one (mpsc is multiple producer single consumer) which is owned by the receiver.
If you need multiple producers and multiple consumers I recommend this crate: https://crates.io/crates/async-channel
The same pattern applies. No arc, no mutex, just clone the sender and receiver handles for each producer and consumer respectively.
Don’t worry about the cloning, channels are specifically designed to be used this way.
The problem might be the arc mutex. mpsc are already clone, send and sync. When you clone an arc mutex T, you are cloning the arc. But mpsc probably needs to be cloned itself to work properly.