channel的几种用法
This commit is contained in:
40
channel/001/main.go
Normal file
40
channel/001/main.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"os/signal"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 两个服务一直产生数据
|
||||
// 希望有数据产生就拿这些数据做一些处理
|
||||
|
||||
// 切换着打印,从1到2
|
||||
func main() {
|
||||
m1, m2 := genMsg("service1"), genMsg("service2")
|
||||
quit := make(chan os.Signal, 1)
|
||||
go func() {
|
||||
for {
|
||||
fmt.Println(<-m1)
|
||||
fmt.Println(<-m2)
|
||||
}
|
||||
}()
|
||||
signal.Notify(quit, os.Interrupt)
|
||||
<-quit
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user