Created
May 7, 2013 19:24
-
-
Save alecbz/5535402 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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