channel的几种用法
This commit is contained in:
50
channel/002/main.go
Normal file
50
channel/002/main.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user