PracticeDev/study_go/concurrency.go

65 lines
982 B
Go
Raw Normal View History

2022-12-20 17:31:11 +08:00
package main
import (
"fmt"
// "sync"
// "math"
"time"
)
func main() {
// var wg sync.WaitGroup
// 事件生成器
ch := make(chan string)
go func() {
ch <- "first"
for i :=0 ;; i++ {
ch <- fmt.Sprintf("%v, hhh", i)
time.Sleep(time.Second)
if (i>2) {
i = 0
}
}
}()
// 事件接收器(重复事件执行一次)
eventMap := make(map[string]bool)
go func() {
for {
x := <-ch
eventMap[x] = true
fmt.Printf("recv event: %v\n", x)
}
}()
// 事件处理器
go func() {
for {
if (len(eventMap) > 0) {
worker(eventMap)
eventMap = make(map[string]bool)
}
time.Sleep(time.Second * 10)
}
}()
for {
time.Sleep(time.Second)
}
// for i := 0; i < math.MaxInt32; i++ {
// wg.Add(1)
// go func(i int) {
// defer wg.Done()
// fmt.Println(i)
// time.Sleep(time.Second)
// }(i)
// }
// wg.Wait()
}
func worker(evMap map[string]bool) {
for k,_ := range(evMap) {
fmt.Printf("Handle %v\n", k)
}
}