init
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
for i := range merge(source(5), source(10), source(20)) {
|
||||
fmt.Printf("%20d\n", i)
|
||||
}
|
||||
}
|
||||
|
||||
func source(c int) <-chan int {
|
||||
out := make(chan int)
|
||||
go func() {
|
||||
vals := make([]int, c)
|
||||
src := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
for i := 0; i < c; i++ {
|
||||
vals[i] = src.Int()
|
||||
}
|
||||
|
||||
sort.Ints(vals)
|
||||
|
||||
for _, i := range vals {
|
||||
out <- i
|
||||
}
|
||||
close(out)
|
||||
}()
|
||||
return out
|
||||
}
|
||||
|
||||
func merge(cs ...<-chan int) <-chan int {
|
||||
wg := sync.WaitGroup{}
|
||||
out := make(chan int)
|
||||
|
||||
output := func(c <-chan int) {
|
||||
for n := range c {
|
||||
out <- n
|
||||
}
|
||||
wg.Done()
|
||||
}
|
||||
|
||||
wg.Add(len(cs))
|
||||
for _, c := range cs {
|
||||
go output(c)
|
||||
}
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(out)
|
||||
}()
|
||||
return out
|
||||
}
|
||||
Reference in New Issue
Block a user