Fragment Description:



Select in a few words:
If one or more of the 'communications' (a case is a communication) can proceed, single one that can proceed is chosen via a uniform pseudo-random selection.
Otherwise, if there is a default case, that case is chosen.
If there is no default case, the 'select' statement blocks until at least one of the communications can proceed.
Must read:
http://golang.org/ref/spec#Select_statements


selectStatement

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:30

/* ... <== see fragment description ... */

package main

import (
    "fmt"
    "runtime"
    "time"
)

func main() {
    runtime.GOMAXPROCS(1)
    ch1 := make(chan int)
    ch2 := make(chan int)
    go pump1(ch1)
    go pump2(ch2)
    go suck(ch1, ch2)
    // extremely short sleep
    time.Sleep(0.000002e9)
}
func pump1(ch chan int) {
    for i := 0; ; i++ {
        ch <- i * 2
    }
}
func pump2(ch chan int) {
    for i := 0; ; i++ {
        ch <- i + 5
    }
}
func suck(ch1, ch2 chan int) {
    for {
        // select chooses the case that is receiving via a pseudo-random selection
        select {
        case v := <-ch1:
            fmt.Println("on line 1", v)
        case v := <-ch2:
            fmt.Println("on line 2", v)
        }
    }
}

/* Expected Output:
on line 2 5
on line 1 0
on line 1 2
on line 1 4
on line 2 6
on line 1 6
on line 2 7
on line 1 8
on line 2 8
on line 1 10
etc..
*/



Comments