Created
October 15, 2020 09:03
-
-
Save gt-sun/3bcb257225368a2d6307001334f84ea2 to your computer and use it in GitHub Desktop.
Golang chan-in
This file contains 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" | |
"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