Skip to content

Instantly share code, notes, and snippets.

@gt-sun
Created October 15, 2020 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gt-sun/3bcb257225368a2d6307001334f84ea2 to your computer and use it in GitHub Desktop.
Save gt-sun/3bcb257225368a2d6307001334f84ea2 to your computer and use it in GitHub Desktop.
Golang chan-in
package main
import (
"fmt"
"sync"
"time"
)
func main() {
a := asChan(1, 2, 3, 4, 5)
b := asChan(6, 7, 8, 9, 0)
out := merge(a, b)
for n := range out {
fmt.Println(n)
}
}
func merge(in ...<-chan int) <-chan int {
out := make(chan int)
var wg sync.WaitGroup
wg.Add(len(in))
for _, i := range in {
go func(i <-chan int) {
for n := range i {
out <- n
}
wg.Done()
}(i)
}
go func() {
wg.Wait()
time.Sleep(time.Second * 3)
close(out)
}()
return out
}
func asChan(in ...int) <-chan int {
out := make(chan int)
go func() {
for _, i := range in {
out <- i
// time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
}
close(out)
}()
return out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment