I was going through the *"Go Design Pattern"* talk by Rob Pike.

Can some one explain me the doubt I am having in the slide Timeout using 
Select <https://talks.golang.org/2012/concurrency.slide#35>. In the the 
video this <https://youtu.be/f6kdp27TYZs?t=1368> is the location where it 
is explained.

The code in the slide returns if there is nothing returned by boring for 1 
second.

Is my below understanding correct:-

So when the program starts let say the below code is executed 

case <- time.After(1 * time.Second)

fmt.Println("You're too slow.") 

return 

before the below:-

case s := <- c
fmt.Println(s) 


So a timer is started for 1 second. Before 1 second is over let's say boring 
writes something to channel c then case s := <- c will be executed. The 
moment somthing is written on channel c the timer that was started gets 
garbage collected and therefore it never returns the current time on the 
channel after 1 second?

I am pasting the code below:-

func boring(msg string) <-chan string { // Returns receive-only channel of 
strings.

    c := make(chan string)
    go func() { // We launch the goroutine from inside the function.
        for i := 0; ; i++ {
            c <- fmt.Sprintf("%s %d", msg, i)
            time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
        }
    }()
    return c // Return the channel to the caller.
}


func main() {
    c := boring("Joe")
    for {
        select {
        case s := <-c:
            fmt.Println(s)
        case <-time.After(1 * time.Second):
            fmt.Println("You're too slow.")
            return
        }
    }
}

-- 
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.

Reply via email to