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

51 lines
905 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"
)
// 有两个服务会产生数据
// 希望有数据就处理
// 希望不要交替执行,谁有就处理谁
// 方案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
}