FAQ

On Wed, Mar 2, 2016 at 12:58 PM, Tapio Raevaara wrote:
I have to admit that I've always wondered why send and receive operations on
nil channel don't simply panic. Am I overlooking something obvious here?
When is permanent blocking *ever* desirable behaviour in this case?
I'm assuming that by "nil" channel you mean one that has nothing in it?

There are lots of use cases for this; in fact, it's an important part
of using channels. For example, you might use this blocking to create
a simple semaphore using channels:

     sem := make(chan int, MaxJobs)

     func SomeJobHandler(queue chan *Job) {
         for job := range queue {
             job := job // Copy and shadow request since Go reuses vars
declared in the for statement
             sem <- 1// Will block after the buffer is full, eg. when
MaxJobs are running
             go func() {
               process(job) // Some expensive processing
               <-sem
             }()
         }
     }

Of course, this can be handled in other ways, but this is just an example.
Another common example can be found in the time package (the first
case won't be hit until the timeout time has passed):

     select {
     case <-After(timeout): // This is similar to calling sleep, except
that we can use it in a select statement where we definitely don't
want the read to panic!
         return // We've timed out
     default:
         // Do some work
     }

These are just a few simple examples of why we might want to block on
a channel read.


--
Sam Whited
pub 4096R/54083AE104EA7AD3
https://blog.samwhited.com

--
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+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Discussion Posts

Previous

Follow ups

Related Discussions

People

Translate

site design / logo © 2022 Grokbase