course/sync/sync.once.go

43 lines
657 B
Go

package main
import "sync"
//某些操作只需要在高并发场景中做一次,例如加载配置文件
//这种场景下用到sync.once
var waitGroup sync.WaitGroup
var once sync.Once
func send(ch1 chan<- int) {
defer waitGroup.Done()
for i := 0; i < 100; i++ {
ch1 <- i
}
close(ch1)
}
func getV(ch1 <-chan int, ch2 chan<- int) {
defer waitGroup.Done()
for {
x, ok := <-ch1
if !ok {
break
}
ch2 <- x * x
}
once.Do(func() { close(ch2) })
}
func main() {
a := make(chan int, 100)
b := make(chan int, 100)
waitGroup.Add(3)
go send(a)
go getV(a, b)
go getV(a, b)
waitGroup.Wait()
for ret := range b {
println(ret)
}
}