Here is an exercise using channels and select in a goroutine.  If the 
disconnect channel is changed to a buffered channel the goroutine doesn't 
run at all.

Why does changing from an unbuffered to a buffered channel prevent running 
the goroutine?

   








































* func SelectDemo(wg *sync.WaitGroup) {                messageCh := 
make(chan int, 10)            disconnectCh := make(chan struct{})          
  //        go routine won't run if channel is buffered            
//disconnectCh := make(chan struct{}, 1)                defer 
close(messageCh)            defer close(disconnectCh)            go func() 
{                    fmt.Println("  goroutine")                    
wg.Add(1)                    for {                            select {      
                      case v := <-messageCh:                                
    fmt.Println(v)                            case <-disconnectCh:          
                          fmt.Println("  disconnectCh")                    
//  empty the message channel before exiting                                
    for {                                            select {              
                              case v := <-messageCh:                        
                            fmt.Println(v)                                  
          default:                                                    
fmt.Println("  disconnection, return")                                      
              wg.Done()                                                    
return                                            }                        
            }                            }                    }            
}()                fmt.Println("Sending ints")            for i := 0; i < 
10; i++ {                    messageCh <- i            }                
fmt.Println("Sending done")            disconnectCh <- struct{}{}    }*
Here's the code to call the function from main.  I use the wait group to 
assure that the goroutine completes before the program exits:

        

*wg := sync.WaitGroup{}        ch09.SelectDemo(&wg)        wg.Wait()*

-- 
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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/533e6da1-e529-4cd3-a18d-1a4ccf09b947n%40googlegroups.com.

Reply via email to