How to tell if `crossbeam_channel` is open before sending? Edit: How to tell if thread is alive?

How can I tell if a crossbeam_channel is open before I send something? It is possible that the thread I’m sending to panicked or returned, but it appears that when the channel is closed the send method just blocks.

Here is an example playground.

I would like to be able to check if the channel has been closed and then terminate the sending thread if possible. But I can’t find a way in the documentation to check the status of the channel if all I have is the sender.

Edit: After further investigation a better question might be “how to tell if a thread is still alive?”

I guess crossbeam will leave the channel open even if the thread terminates, so it is not closed at all, however, the receiver has been dropped.

This seems like a deficiency in crossbeam-channel’s API. Sender::send should return some kind of error if the Receiver has dropped. Trying to figure out if the thread is still alive isn’t really a robust fix since there’s always a race condition of the thread exiting after you check but before it receives a value.

Edit: There’s some discussion of the issue here: https://github.com/crossbeam-rs/crossbeam-channel/issues/61

1 Like

Thanks for the link to the issue. Of course it is more complex than I initially thought. I would just use the std channels, but they are unbounded and I need the back-pressure to keep from using all of my machines memory.

@ryan you can use sync_channel for that!

1 Like

Thanks @jethrogb, I hadn’t seen that before. I already figured out another way by making another channel that signals an error. I like this, I think it would make the code much simpler.

But now that I went to the trouble to set up the other way, I’m using that new channel to propagate the error that caused the thread to shut down early. It looks like this will only send back the original value that I sent.

FYI: I’m using channels to set up a single thread that handles all DB communication in my app. So I need two way communication. That has made this all much more difficult.

Thanks, again.

Thank you! I’ve gone through two iterations of my “shut down protocol” since I started this thread. I’ve found they either hang on errors or get convoluted quickly. I think this will help me clean up the channels quite a bit.