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

50
channel/002/main.go Normal file
View File

@@ -0,0 +1,50 @@
package main
import (
"fmt"
"math/rand"
"time"
)
// 有两个服务会产生数据
// 希望有数据就处理
// 希望不要交替执行,谁有就处理谁
// 方案1: 起一个函数这两个channel有数据就把这个数据给到另外一个channel然后读取另外一个channel
func main() {
m1, m2 := genMsg("service1"), genMsg("service2")
m := merge(m1, m2)
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
}
// 将两个channel里的数据送到另外一个channel里
func merge(c1, c2 chan string) chan string {
c := make(chan string)
go func() {
for {
c <- <-c1
}
}()
go func() {
for {
c <- <-c2
}
}()
return c
}