golanglearn/channel/004/main.go
2022-01-16 18:26:27 +08:00

47 lines
820 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"fmt"
"math/rand"
"time"
)
// 现在有n个服务每个服务都产生数据
// 产生数据就做处理
// 需要服务里有数据,就打印谁的
// 有个可变长度的 chan of string 遍历
func main() {
m1, m2, m3 := genMsg("service1"), genMsg("service2"), genMsg("service3")
m := merge(m1, m2, m3)
for {
fmt.Println(<-m)
}
}
func genMsg(name string) chan string {
c := make(chan string)
go func() {
i := 0
for {
time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
c <- fmt.Sprintf("the service name is %v,the message is %v", name, i)
i++
}
}()
return c
}
func merge(chs ...chan string) chan string {
c := make(chan string)
for _, ch := range chs {
//copy := ch
go func(a chan string) {
for {
c <- <-a
}
}(ch)
}
return c
}