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

52 lines
854 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"
)
// select
// 有两个服务都产生数据
// 有产生数据,就做处理
// 谁有数据就处理谁
// 不要用将两个channel里的数据写到新的channel里然后再读这个channel
func main() {
m1, m2 := genMsg("service1"), genMsg("service2")
m := useSelect(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
}
// 使用select监控channel
func useSelect(c1, c2 chan string) chan string {
c := make(chan string)
go func() {
for {
select {
case m := <-c1:
c <- m
case m := <-c2:
c <- m
}
}
}()
return c
}