4 ms·
You can check if a channel is closed or not. You can even use it gracefully as an iterator.
by integrii 10y ago
You can check if a channel is closed or not. You can even use it gracefully as an iterator.
- nothrabannosir 10y agoBoth you and parent are right. To be exact: you cannot "non-destructively" check if a channel is closed. I.e.: the way to check is by using a select statement to do a "soft write", I.e. "try to send this value but don't panic if it fails." Same for reading. This means you can't check the state of a channel without modifying it if it isn't closed.
- frou_dh 10y agoThat reminds me of Unix FDs and the distinction between whether your user has permission to write a file, and whether an open file is actually open-for-writing. I was thankful to find out about fcntl(2) + F_GETFL, and get out of a 'dummy write' train of thought.
- dom0 10y agoFun-fact: In the POSIX model you cannot write into a private mapping created through a FD with the writable bit not set. (Or, more precisely, Linux won't let you set the write bit of the mapping). Even though that would be a rather useful thing to have, and wouldn't be hindered by hardware or kernel (which already does CoW of pages).
- gpderetta 10y agoI know nothing about go, but assuming the reading end of the channel is running concurrently, the only way to meaningfully check for closeness is actually trying, any other check would be meaningless as an open channel could have been closed immediately after the check would have returned 'closed'.
- Animats 10y agoSending to a closed channel is fatal, as is closing it. There's no way for multiple senders sending to a channel to tell if somebody closed it without risk of crashing. Graceful shutdown of systems with lots of asynchronous communication is hard, but this makes it harder than it has to be.
- nothrabannosir 10y agoI was wrong; this is true. the soft-reading thing only works for reading. You can't soft-write with select to a closed channel, it will crash even with a default clause. *sigh, after all that time I still make this mistake. Goes to show how often I actually use channels. :/