channel的几种用法

This commit is contained in:
2022-01-16 18:26:27 +08:00
commit f769f2b57d
6 changed files with 191 additions and 0 deletions

46
channel/004/main.go Normal file
View File

@@ -0,0 +1,46 @@
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
}