1

I need a variant of Crossbeam's zero-capacity channel, crossbeam_channel::bounded(0), which does not block on send() if there is no receive operation. In my case, messages that are sent while there is no receive operation in progress can be discarded. A receiver will receive all the messages sent after it started listening. This is similar to what happens with Redis channels, but between threads.

Does something like this exist already or do I need to implement it myself? At the moment it's not clear to me how such a functionality would be implemented, but I can probably start by looking at the implementation of the bounded zero-capacity channel and possibly replace the blocking send operation with a non-blocking version.

rubik
  • 8,814
  • 9
  • 58
  • 88
  • Is this what you are looking for? [`crossbeam_channel::Sender::try_send()`](https://docs.rs/crossbeam-channel/0.4.4/crossbeam_channel/struct.Sender.html#method.try_send) – Sven Marnach Sep 23 '20 at 07:57
  • @SvenMarnach Yes, I was about to edit my question. By looking at the source I found out that zero-capacity channels have `try_send` too. From the documentation it wasn't clear in my opinion. – rubik Sep 23 '20 at 08:01
  • Why do you think this wasn't clear from the documentation? You can click the types returned by `crossbeam_channel::bounded()` on its [documentation page](https://docs.rs/crossbeam-channel/0.4.4/crossbeam_channel/fn.bounded.html), and it will show you the methods these types provide. – Sven Marnach Sep 23 '20 at 08:05
  • Also note that the senders for bounded and unbounded channels have the same type, `crossbeam_channel::Sender`. – Sven Marnach Sep 23 '20 at 08:06
  • @SvenMarnach If you turn that into an answer I will accept it. Otherwise, I am not sure what is the recommended course of action here, should I just close or delete the question? – rubik Sep 23 '20 at 08:07
  • @SvenMarnach The reason it wasn't clear to me was that zero-capacity channels are only mentioned in the contest of blocking send operations. The example only shows that. Yes, the return types make it clear, I agree. – rubik Sep 23 '20 at 08:08
  • 1
    Keep the question – it may be useful for other people as well. I'll turn my comment into an answer. – Sven Marnach Sep 23 '20 at 08:15

1 Answers1

3

All crossbeam channels offer a non-blocking version of the send() method as well. It's called try_send(), and it returns an error in case the message could not be sent. For a zero-capacity channel, this result in exactly the behaviour you ask for – the message will only be sent "if there happens to be a receive operation on the other side of the channel at the same time" (quote from the docs).

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841