Skip to content

Instantly share code, notes, and snippets.

@alecbz
Created May 7, 2013 19:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alecbz/5535402 to your computer and use it in GitHub Desktop.
Save alecbz/5535402 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"reflect"
)
func worker(n int, ch chan int) {
count := rand.Intn(5) + 3
x := n
for i := 0; i < count; i++ {
ch <- x
x *= n
}
close(ch)
}
const N = 5
func main() {
chs := make([]chan int, N)
for i := 0; i < N; i++ {
chs[i] = make(chan int)
go worker(2 + i, chs[i])
}
selectCases := make([]reflect.SelectCase, N)
for i := 0; i < N; i++ {
selectCases[i].Dir = reflect.SelectRecv
selectCases[i].Chan = reflect.ValueOf(chs[i])
}
numDone := 0
for numDone < N {
chosen, recv, recvOk := reflect.Select(selectCases)
if recvOk {
fmt.Printf("From %d: %d\n", 2 + chosen, recv.Int())
} else {
numDone++
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment