On Sunday, 28 August 2016 17:33:10 UTC+2, Jan Mercl wrote: > > Using len(ch) like this in a concurrency scenario is a big no because then > the value you get carries 0 bits of useful information. It's not a data > race, it's worse, the race is semantic and not fixable without removing the > use of len(ch). >
In general I would agree, if you know other things, it *can* contain useful information. I recently had some code, where using "len(channel)" was actually useful, since it allowed me to do a proper shutdown of a queue+retry queue with relatively simple code. I tried to boil it down as an example: https://play.golang.org/p/DMcl8k5Ssx I want to receive messages to a bunch of workers, but they must be able to add the entry to a "retry queue" under certain conditions. If I just add them back to the original channel I risk a deadlock, so I have i prioritized queue (channel) for that. Furthermore I must ensure that all messages are processed when we exit, that means both the queue and retry queue must be empty. In this case, using the length is useful, since it ensure that the last worker will not exit if there are tasks still in the retry queue - since only tasks (and functions called by the task) can add stuff to the retry queue. For this, I found len(channel) to be both useful and aiding (for what I can come up with) the simplest solution. I think that in my 4 years of programming Go, it is probably the first time I have encountered it ;) /Klaus > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.