channel的几种用法
This commit is contained in:
51
channel/003/main.go
Normal file
51
channel/003/main.go
Normal file
@@ -0,0 +1,51 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user