channel的几种用法

This commit is contained in:
2022-01-16 18:26:27 +08:00
commit f769f2b57d
6 changed files with 191 additions and 0 deletions

40
channel/001/main.go Normal file
View 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
}