sync.Once.Do(f func())是一个挺有趣的东西,能保证once只执行一次,无论你是否更换once.Do(xx)这里的方法,这个sync.Once块只会执行一次。
package main
import (
"fmt"
"sync"
"time"
)
var once sync.Once
func main() {
for i, v := range make([]string, 10) {
once.Do(onces)
fmt.Println("count:", v, "---", i)
}
for i := 0; i < 10; i++ {
go func() {
once.Do(onced)
fmt.Println("213")
}()
}
time.Sleep(1 * time.Second)
}
func onces() {
fmt.Println("onces")
}
func onced() {
fmt.Println("onced")
}
运行结果:
root@ubuntn:~/testGo# go run Once.go
onces
count: --- 0
count: --- 1
count: --- 2
count: --- 3
count: --- 4
count: --- 5
count: --- 6
count: --- 7
count: --- 8
count: --- 9
213
213
213
213
213
213
213
213
213
213
整个程序,只会执行onces()方法一次,onced()方法是不会被执行的。
转载出处:https://blog.csdn.net/x369201170/article/details/26019331