Created
August 29, 2019 04:32
-
-
Save maksadbek/11fbb2c047495622687eb875ae6167cf 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" | |
"time" | |
) | |
func mergeWithRange(chans ...chan int) chan int { | |
out := make(chan int) | |
for _, ch := range chans { | |
go func(c chan int) { | |
for v := range c { | |
out <- v | |
} | |
}(ch) | |
} | |
// create a closeChan | |
return out | |
} | |
func mergeWithSelect(chans ...chan int) chan int { | |
outch := make(chan int) | |
closeChan := make(chan struct{}) | |
for _, ch := range chans { | |
go func(c chan int) { | |
for { | |
v, ok := <-c | |
if !ok { | |
closeChan <- struct{}{} | |
return | |
} | |
outch <- v | |
} | |
}(ch) | |
} | |
go func(outChan chan int, closeChan chan struct{}, chanCount int) { | |
counter := 0 | |
for { | |
<-closeChan | |
counter++ | |
if counter == chanCount { | |
close(outChan) | |
} | |
} | |
}(outch, closeChan, len(chans)) | |
return outch | |
} | |
func main() { | |
a := make(chan int) | |
b := make(chan int) | |
c := make(chan int) | |
res := mergeWithSelect(a, b, c) | |
go func() { | |
for v := range res { | |
fmt.Println(v) | |
} | |
println("close!") | |
}() | |
a <- 1 | |
b <- 2 | |
a <- 3 | |
close(a) | |
close(b) | |
close(c) | |
time.Sleep(time.Second * 3) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment