Crossbeam zero-capacity channel which does not block on send

640 views Asked by At

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.

1

There are 1 answers

0
Sven Marnach On BEST ANSWER

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).