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

41 lines
676 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"
"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
}