Created
June 15, 2013 23:49
-
-
Save samuell/5790078 to your computer and use it in GitHub Desktop.
This code snippet describes how to read a "select statement" based fan-in channel in Go, as a range, without deadlocks or strange race conditions. The key to get this right is to use "ok-variables" from the input channels to see if they are closed, and if so, set the channels to nil. Then, if in the for loop you continue until both inputs are ni…
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" | |
| import "time" | |
| //import "runtime" | |
| func numberGenerator() <-chan int { | |
| c := make(chan int) | |
| go func() { | |
| for i := 1; i <= 10; i++ { | |
| c <- i | |
| time.Sleep(1000) | |
| } | |
| close(c) | |
| }() | |
| return c | |
| } | |
| func fanIn(input1, input2 <-chan int) <-chan int { | |
| c := make(chan int) | |
| go func() { | |
| for input1 != nil || input2 != nil { | |
| select { | |
| case v, ok1 := <-input1: | |
| if !ok1 { | |
| input1 = nil | |
| fmt.Println("Set input1 to nil") | |
| continue | |
| } | |
| c <- v | |
| case v, ok2 := <-input2: | |
| if !ok2 { | |
| input2 = nil | |
| fmt.Println("Set input2 to nil") | |
| continue | |
| } | |
| c <- v | |
| } | |
| } | |
| close(c) | |
| fmt.Println("Closed fan in chan") | |
| return | |
| }() | |
| return c | |
| } | |
| func main() { | |
| //runtime.GOMAXPROCS(2) | |
| c1 := numberGenerator() | |
| c2 := numberGenerator() | |
| cfanin := fanIn(c1, c2) | |
| for v := range cfanin { | |
| fmt.Println(v) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment